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 <Airports/dynamics.hxx>
72 #include <AIModel/AIManager.hxx>
73 #include <ATCDCL/ATCmgr.hxx>
74 #include <ATCDCL/AIMgr.hxx>
75 #include <Autopilot/route_mgr.hxx>
76 #include <Autopilot/xmlauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/panel.hxx>
79 #include <Cockpit/panel_io.hxx>
81 #include <FDM/SP/ADA.hxx>
82 #include <FDM/SP/ACMS.hxx>
83 #include <FDM/SP/MagicCarpet.hxx>
84 #include <FDM/SP/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/UFO.hxx>
91 #include <FDM/NullFDM.hxx>
92 #include <FDM/YASim/YASim.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Include/general.hxx>
95 #include <Input/input.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Model/acmodel.hxx>
98 #include <AIModel/submodel.hxx>
99 #include <AIModel/AIManager.hxx>
100 #include <Navaids/navdb.hxx>
101 #include <Navaids/navlist.hxx>
102 #include <Scenery/scenery.hxx>
103 #include <Scenery/tilemgr.hxx>
104 #include <Scripting/NasalSys.hxx>
105 #include <Sound/fg_fx.hxx>
106 #include <Sound/beacon.hxx>
107 #include <Sound/morse.hxx>
108 #include <Sound/voice.hxx>
109 #include <Systems/system_mgr.hxx>
110 #include <Time/light.hxx>
111 #include <Time/sunsolver.hxx>
112 #include <Time/tmp.hxx>
113 #include <Traffic/TrafficMgr.hxx>
114 #include <MultiPlayer/multiplaymgr.hxx>
116 #include <Environment/environment_mgr.hxx>
118 #include "fg_init.hxx"
120 #include "fg_commands.hxx"
121 #include "fg_props.hxx"
122 #include "options.hxx"
123 #include "globals.hxx"
124 #include "logger.hxx"
125 #include "renderer.hxx"
126 #include "viewmgr.hxx"
130 # include <CoreFoundation/CoreFoundation.h>
136 extern const char *default_root;
140 // Scan the command line options for the specified option and return
142 static string fgScanForOption( const string& option, int argc, char **argv ) {
145 if (hostname == NULL)
148 gethostname(_hostname, 256);
149 hostname = strdup(_hostname);
150 free_hostname = true;
153 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
155 int len = option.length();
158 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
160 string arg = argv[i];
161 if ( arg.find( option ) == 0 ) {
162 return arg.substr( len );
172 // Scan the user config files for the specified option and return
174 static string fgScanForOption( const string& option, const string& path ) {
175 sg_gzifstream in( path );
176 if ( !in.is_open() ) {
180 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
182 int len = option.length();
185 while ( ! in.eof() ) {
187 getline( in, line, '\n' );
189 // catch extraneous (DOS) line ending character
190 if ( line[line.length() - 1] < 32 ) {
191 line = line.substr( 0, line.length()-1 );
194 if ( line.find( option ) == 0 ) {
195 return line.substr( len );
204 // Scan the user config files for the specified option and return
206 static string fgScanForOption( const string& option ) {
209 #if defined( unix ) || defined( __CYGWIN__ )
210 // Next check home directory for .fgfsrc.hostname file
212 if ( homedir != NULL ) {
213 SGPath config( homedir );
214 config.append( ".fgfsrc" );
215 config.concat( "." );
216 config.concat( hostname );
217 arg = fgScanForOption( option, config.str() );
222 // Next check home directory for .fgfsrc file
224 if ( homedir != NULL ) {
225 SGPath config( homedir );
226 config.append( ".fgfsrc" );
227 arg = fgScanForOption( option, config.str() );
232 // Check for $fg_root/system.fgfsrc
233 SGPath config( globals->get_fg_root() );
234 config.append( "system.fgfsrc" );
235 arg = fgScanForOption( option, config.str() );
242 // Read in configuration (files and command line options) but only set
244 bool fgInitFGRoot ( int argc, char **argv ) {
247 // First parse command line options looking for --fg-root=, this
248 // will override anything specified in a config file
249 root = fgScanForOption( "--fg-root=", argc, argv);
251 // Check in one of the user configuration files.
253 root = fgScanForOption( "--fg-root=" );
255 // Next check if fg-root is set as an env variable
256 if ( root.empty() ) {
257 char *envp = ::getenv( "FG_ROOT" );
258 if ( envp != NULL ) {
263 // Otherwise, default to a random compiled-in location if we can't
264 // find fg-root any other way.
265 if ( root.empty() ) {
266 #if defined( __CYGWIN__ )
267 root = "/FlightGear";
268 #elif defined( WIN32 )
269 root = "\\FlightGear";
270 #elif defined(__APPLE__)
272 The following code looks for the base package inside the application
273 bundle, in the standard Contents/Resources location.
275 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
277 // look for a 'data' subdir
278 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
280 // now convert down to a path, and the a c-string
281 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
282 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
284 CFRelease(resourcesUrl);
292 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
293 globals->set_fg_root(root);
299 // Read in configuration (files and command line options) but only set
301 bool fgInitFGAircraft ( int argc, char **argv ) {
304 // First parse command line options looking for --aircraft=, this
305 // will override anything specified in a config file
306 aircraft = fgScanForOption( "--aircraft=", argc, argv );
307 if ( aircraft.empty() ) {
308 // check synonym option
309 aircraft = fgScanForOption( "--vehicle=", argc, argv );
312 // Check in one of the user configuration files.
313 if ( aircraft.empty() ) {
314 aircraft = fgScanForOption( "--aircraft=" );
316 if ( aircraft.empty() ) {
317 aircraft = fgScanForOption( "--vehicle=" );
320 // if an aircraft was specified, set the property name
321 if ( !aircraft.empty() ) {
322 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
323 fgSetString("/sim/aircraft", aircraft.c_str() );
325 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
332 // Return the current base package version
333 string fgBasePackageVersion() {
334 SGPath base_path( globals->get_fg_root() );
335 base_path.append("version");
337 sg_gzifstream in( base_path.str() );
338 if ( !in.is_open() ) {
339 SGPath old_path( globals->get_fg_root() );
340 old_path.append( "Thanks" );
341 sg_gzifstream old( old_path.str() );
342 if ( !old.is_open() ) {
345 return "[old version]";
356 // Initialize the localization
357 SGPropertyNode *fgInitLocale(const char *language) {
358 SGPropertyNode *c_node = NULL, *d_node = NULL;
359 SGPropertyNode *intl = fgGetNode("/sim/intl");
361 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
363 // localization not defined
368 // Select the proper language from the list
370 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
371 for (unsigned int i = 0; i < locale.size(); i++) {
373 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
374 for (unsigned int j = 0; j < lang.size(); j++) {
376 if (!strcmp(lang[j]->getStringValue(), language)) {
385 d_node = intl->getChild("locale");
389 // Check for localized font
390 SGPropertyNode *font_n = c_node->getNode("font", true);
391 if ( !strcmp(font_n->getStringValue(), "") )
392 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
396 // Load the default strings
398 SGPath d_path( globals->get_fg_root() );
400 const char *d_path_str = d_node->getStringValue("strings");
402 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
406 d_path.append(d_path_str);
407 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
409 SGPropertyNode *strings = c_node->getNode("strings");
411 readProperties(d_path.str(), strings);
412 } catch (const sg_exception &) {
413 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
418 // Load the language specific strings
420 if (c_node != d_node) {
421 SGPath c_path( globals->get_fg_root() );
423 const char *c_path_str = c_node->getStringValue("strings");
425 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
429 c_path.append(c_path_str);
430 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
433 readProperties(c_path.str(), strings);
434 } catch (const sg_exception &) {
435 SG_LOG(SG_GENERAL, SG_ALERT,
436 "Unable to read the localized strings from " << c_path.str());
446 // Initialize the localization routines
447 bool fgDetectLanguage() {
448 const char *language = ::getenv("LANG");
450 if (language == NULL) {
451 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
455 SGPropertyNode *locale = fgInitLocale(language);
457 SG_LOG(SG_GENERAL, SG_ALERT,
458 "No internationalization settings specified in preferences.xml" );
463 globals->set_locale( locale );
468 // Attempt to locate and parse the various non-XML config files in order
469 // from least precidence to greatest precidence
471 do_options (int argc, char ** argv)
473 // Check for $fg_root/system.fgfsrc
474 SGPath config( globals->get_fg_root() );
475 config.append( "system.fgfsrc" );
476 fgParseOptions(config.str());
478 #if defined( unix ) || defined( __CYGWIN__ )
479 config.concat( "." );
480 config.concat( hostname );
481 fgParseOptions(config.str());
484 // Check for ~/.fgfsrc
485 if ( homedir != NULL ) {
486 config.set( homedir );
487 config.append( ".fgfsrc" );
488 fgParseOptions(config.str());
491 #if defined( unix ) || defined( __CYGWIN__ )
492 // Check for ~/.fgfsrc.hostname
493 config.concat( "." );
494 config.concat( hostname );
495 fgParseOptions(config.str());
498 // Parse remaining command line options
499 // These will override anything specified in a config file
500 fgParseArgs(argc, argv);
504 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
505 SGPropertyNode *cache, int depth = 0 )
507 const int MAXDEPTH = 1;
510 ulDir *dirp = ulOpenDir(path.str().c_str());
512 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
517 while ((dire = ulReadDir(dirp)) != NULL) {
519 if (depth > MAXDEPTH)
522 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
523 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
527 next.append(dire->d_name);
529 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
530 if ( ! result.empty() )
534 int len = strlen(dire->d_name);
535 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
541 if (!cache->getChild("aircraft", i++, false))
544 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
546 n = entry->getNode("file", true);
547 n->setStringValue(dire->d_name);
548 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
550 n = entry->getNode("path", true);
551 n->setStringValue(path.str().c_str());
552 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
554 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
566 // Read in configuration (file and command line)
567 bool fgInitConfig ( int argc, char **argv ) {
569 // First, set some sane default values
572 // Read global preferences from $FG_ROOT/preferences.xml
573 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
574 fgLoadProps("preferences.xml", globals->get_props());
575 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
577 // Detect the required language as early as possible
578 if ( !fgDetectLanguage() ) {
582 SGPropertyNode autosave;
584 char *envp = ::getenv( "APPDATA" );
586 SGPath config( envp );
587 config.append( "flightgear.org" );
589 if ( homedir != NULL ) {
590 SGPath config( homedir );
591 config.append( ".fgfs" );
593 const char *fg_home = getenv("FG_HOME");
597 // Set /sim/fg-home and don't allow malign code to override it until
598 // Nasal security is set up. Use FG_HOME if necessary.
599 SGPropertyNode *home = fgGetNode("/sim", true);
600 home->removeChild("fg-home", 0, false);
601 home = home->getChild("fg-home", 0, true);
602 home->setStringValue(config.c_str());
603 home->setAttribute(SGPropertyNode::WRITE, false);
605 config.append( "autosave.xml" );
606 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
608 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
610 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
612 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
614 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
617 // Scan user config files and command line for a specified aircraft.
618 fgInitFGAircraft(argc, argv);
620 string aircraft = fgGetString( "/sim/aircraft", "" );
621 if ( aircraft.size() > 0 ) {
622 SGPath aircraft_search( globals->get_fg_root() );
623 aircraft_search.append( "Aircraft" );
625 string aircraft_set = aircraft + "-set.xml";
628 // check if the *-set.xml file is already in the cache
629 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
630 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
631 for (unsigned int i = 0; i < cache.size(); i++) {
632 const char *name = cache[i]->getStringValue("file", "");
633 if (aircraft_set == name) {
634 const char *path = cache[i]->getStringValue("path", "");
644 if (result.empty()) {
645 // prepare cache for rescan
646 SGPropertyNode *n = cache_root->getNode("fg-root", true);
647 n->setStringValue(globals->get_fg_root().c_str());
648 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
649 cache_root->removeChildren("aircraft");
651 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
654 if ( !result.empty() ) {
655 fgSetString( "/sim/aircraft-dir", result.c_str() );
656 SGPath full_name( result );
657 full_name.append( aircraft_set );
659 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
660 << " from " << full_name.str());
662 readProperties( full_name.str(), globals->get_props() );
663 } catch ( const sg_exception &e ) {
664 string message = "Error reading default aircraft: ";
665 message += e.getFormattedMessage();
666 SG_LOG(SG_INPUT, SG_ALERT, message);
670 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
676 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
679 copyProperties(&autosave, globals->get_props());
681 // parse options after loading aircraft to ensure any user
682 // overrides of defaults are honored.
683 do_options(argc, argv);
694 // This function is never used, but maybe useful in the future ???
697 // Preset lon/lat given an airport id
698 static bool fgSetPosFromAirportID( const string& id ) {
702 SG_LOG( SG_GENERAL, SG_INFO,
703 "Attempting to set starting position from airport code " << id );
705 if ( fgFindAirportID( id, &a ) ) {
707 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
708 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
710 // other code depends on the actual postition being set so set
712 fgSetDouble("/position/longitude-deg", a->longitude );
713 fgSetDouble("/position/latitude-deg", a->latitude );
715 SG_LOG( SG_GENERAL, SG_INFO,
716 "Position for " << id << " is (" << a->longitude
717 << ", " << a->latitude << ")" );
727 // Set current tower position lon/lat given an airport id
728 static bool fgSetTowerPosFromAirportID( const string& id) {
729 const FGAirport *a = fgFindAirportID( id);
731 SGGeod tower = a->getTowerLocation();
732 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
733 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
734 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
742 struct FGTowerLocationListener : SGPropertyChangeListener {
743 void valueChanged(SGPropertyNode* node) {
744 const string id(node->getStringValue());
745 fgSetTowerPosFromAirportID(id);
749 void fgInitTowerLocationListener() {
750 fgGetNode("/sim/tower/airport-id", true)
751 ->addChangeListener( new FGTowerLocationListener(), true );
754 // Set current_options lon/lat given an airport id and heading (degrees)
755 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 const FGAirport* apt = fgFindAirportID(id);
765 if (!apt) return false;
766 FGRunway r = apt->findBestRunwayForHeading(tgt_hdg);
767 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
769 double lat2, lon2, az2;
770 double heading = r._heading;
771 double azimuth = heading + 180.0;
772 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
774 SG_LOG( SG_GENERAL, SG_INFO,
775 "runway = " << r._lon << ", " << r._lat
776 << " length = " << r._length * SG_FEET_TO_METER
777 << " heading = " << azimuth );
779 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
780 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
781 &lat2, &lon2, &az2 );
783 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
785 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
786 odist *= SG_NM_TO_METER;
787 double oaz = azimuth;
788 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
789 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
792 while ( oaz >= 360.0 ) { oaz -= 360.0; }
793 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
799 fgSetDouble("/sim/presets/longitude-deg", lon2 );
800 fgSetDouble("/sim/presets/latitude-deg", lat2 );
801 fgSetDouble("/sim/presets/heading-deg", heading );
803 // other code depends on the actual values being set ...
804 fgSetDouble("/position/longitude-deg", lon2 );
805 fgSetDouble("/position/latitude-deg", lat2 );
806 fgSetDouble("/orientation/heading-deg", heading );
808 SG_LOG( SG_GENERAL, SG_INFO,
809 "Position for " << id << " is ("
811 << lat2 << ") new heading is "
817 // Set current_options lon/lat given an airport id and parkig position name
818 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
822 // can't see an easy way around this const_cast at the moment
823 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
825 SG_LOG( SG_GENERAL, SG_ALERT,
826 "Failed to find airport " << id );
829 FGAirportDynamics* dcs = apt->getDynamics();
831 SG_LOG( SG_GENERAL, SG_ALERT,
832 "Failed to find parking position " << parkpos <<
833 " at airport " << id );
837 int park_index = dcs->getNrOfParkings() - 1;
838 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
839 if (park_index < 0) {
840 SG_LOG( SG_GENERAL, SG_ALERT,
841 "Failed to find parking position " << parkpos <<
842 " at airport " << id );
845 FGParking* parking = dcs->getParking(park_index);
847 double lat = parking->getLatitude();
848 double lon = parking->getLongitude();
849 double hdg = parking->getHeading();
852 fgSetDouble("/sim/presets/longitude-deg", lon );
853 fgSetDouble("/sim/presets/latitude-deg", lat );
854 fgSetDouble("/sim/presets/heading-deg", hdg );
856 // other code depends on the actual values being set ...
857 fgSetDouble("/position/longitude-deg", lon );
858 fgSetDouble("/position/latitude-deg", lat );
859 fgSetDouble("/orientation/heading-deg", hdg );
861 SG_LOG( SG_GENERAL, SG_INFO,
862 "Position for " << id << " is ("
864 << lat << ") new heading is "
871 // Set current_options lon/lat given an airport id and runway number
872 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
876 // set initial position from airport and runway number
877 SG_LOG( SG_GENERAL, SG_INFO,
878 "Attempting to set starting position for "
879 << id << ":" << rwy );
881 const FGAirport* apt = fgFindAirportID(id);
883 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
887 if (!apt->hasRunwayWithIdent(rwy)) {
888 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
889 "Failed to find runway " << rwy <<
890 " at airport " << id << ". Using default runway." );
894 FGRunway r(apt->getRunwayByIdent(rwy));
895 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
897 double lat2, lon2, az2;
898 double heading = r._heading;
899 double azimuth = heading + 180.0;
900 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
902 SG_LOG( SG_GENERAL, SG_INFO,
903 "runway = " << r._lon << ", " << r._lat
904 << " length = " << r._length * SG_FEET_TO_METER
905 << " heading = " << azimuth );
907 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
908 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
909 &lat2, &lon2, &az2 );
911 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
914 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
915 odist *= SG_NM_TO_METER;
916 double oaz = azimuth;
917 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
919 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
920 heading = fgGetDouble("/sim/presets/heading-deg");
922 while ( oaz >= 360.0 ) { oaz -= 360.0; }
923 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
929 fgSetDouble("/sim/presets/longitude-deg", lon2 );
930 fgSetDouble("/sim/presets/latitude-deg", lat2 );
931 fgSetDouble("/sim/presets/heading-deg", heading );
933 // other code depends on the actual values being set ...
934 fgSetDouble("/position/longitude-deg", lon2 );
935 fgSetDouble("/position/latitude-deg", lat2 );
936 fgSetDouble("/orientation/heading-deg", heading );
938 SG_LOG( SG_GENERAL, SG_INFO,
939 "Position for " << id << " is ("
941 << lat2 << ") new heading is "
948 static void fgSetDistOrAltFromGlideSlope() {
949 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
950 string apt_id = fgGetString("/sim/presets/airport-id");
951 double gs = fgGetDouble("/sim/presets/glideslope-deg")
952 * SG_DEGREES_TO_RADIANS ;
953 double od = fgGetDouble("/sim/presets/offset-distance-nm");
954 double alt = fgGetDouble("/sim/presets/altitude-ft");
956 double apt_elev = 0.0;
957 if ( ! apt_id.empty() ) {
958 apt_elev = fgGetAirportElev( apt_id );
959 if ( apt_elev < -9990.0 ) {
966 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
967 // set altitude from glideslope and offset-distance
968 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
969 alt = fabs(od*tan(gs)) + apt_elev;
970 fgSetDouble("/sim/presets/altitude-ft", alt);
971 fgSetBool("/sim/presets/onground", false);
972 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
974 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
975 // set offset-distance from glideslope and altitude
976 od = (alt - apt_elev) / tan(gs);
977 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
978 fgSetDouble("/sim/presets/offset-distance-nm", od);
979 fgSetBool("/sim/presets/onground", false);
980 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
982 } else if( fabs(gs) > 0.01 ) {
983 SG_LOG( SG_GENERAL, SG_ALERT,
984 "Glideslope given but not altitude or offset-distance." );
985 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
986 fgSetDouble("/sim/presets/glideslope-deg", 0);
987 fgSetBool("/sim/presets/onground", true);
992 // Set current_options lon/lat given an airport id and heading (degrees)
993 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
995 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
997 // set initial position from runway and heading
999 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1000 << id << ":" << freq );
1002 double lon = nav->get_lon();
1003 double lat = nav->get_lat();
1005 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1007 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1009 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1011 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1012 double olat, olon, az2;
1013 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1020 fgSetDouble("/sim/presets/longitude-deg", lon );
1021 fgSetDouble("/sim/presets/latitude-deg", lat );
1023 // other code depends on the actual values being set ...
1024 fgSetDouble("/position/longitude-deg", lon );
1025 fgSetDouble("/position/latitude-deg", lat );
1026 fgSetDouble("/orientation/heading-deg",
1027 fgGetDouble("/sim/presets/heading-deg") );
1029 SG_LOG( SG_GENERAL, SG_INFO,
1030 "Position for " << id << ":" << freq << " is ("
1031 << lon << ", "<< lat << ")" );
1035 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1036 << id << ":" << freq );
1041 // Set current_options lon/lat given an aircraft carrier id
1042 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1044 // set initial position from runway and heading
1048 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1049 double lon = geodPos.getLongitudeDeg();
1050 double lat = geodPos.getLatitudeDeg();
1051 double alt = geodPos.getElevationFt();
1053 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1054 << carrier << " at lat = " << lat << ", lon = " << lon
1055 << ", alt = " << alt << ", heading = " << heading);
1057 fgSetDouble("/sim/presets/longitude-deg", lon);
1058 fgSetDouble("/sim/presets/latitude-deg", lat);
1059 fgSetDouble("/sim/presets/altitude-ft", alt);
1060 fgSetDouble("/sim/presets/heading-deg", heading);
1061 fgSetDouble("/position/longitude-deg", lon);
1062 fgSetDouble("/position/latitude-deg", lat);
1063 fgSetDouble("/position/altitude-ft", alt);
1064 fgSetDouble("/orientation/heading-deg", heading);
1066 fgSetString("/sim/presets/speed-set", "UVW");
1067 fgSetDouble("/velocities/uBody-fps", uvw(0));
1068 fgSetDouble("/velocities/vBody-fps", uvw(1));
1069 fgSetDouble("/velocities/wBody-fps", uvw(2));
1070 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1071 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1072 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1074 fgSetBool("/sim/presets/onground", true);
1078 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1084 // Set current_options lon/lat given an airport id and heading (degrees)
1085 static bool fgSetPosFromFix( const string& id ) {
1088 // set initial position from runway and heading
1089 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1090 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1093 double lon = fix.get_lon();
1094 double lat = fix.get_lat();
1096 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1098 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1100 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1102 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1103 double olat, olon, az2;
1104 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1111 fgSetDouble("/sim/presets/longitude-deg", lon );
1112 fgSetDouble("/sim/presets/latitude-deg", lat );
1114 // other code depends on the actual values being set ...
1115 fgSetDouble("/position/longitude-deg", lon );
1116 fgSetDouble("/position/latitude-deg", lat );
1117 fgSetDouble("/orientation/heading-deg",
1118 fgGetDouble("/sim/presets/heading-deg") );
1120 SG_LOG( SG_GENERAL, SG_INFO,
1121 "Position for " << id << " is ("
1122 << lon << ", "<< lat << ")" );
1126 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1134 * Initialize vor/ndb/ils/fix list management and query systems (as
1135 * well as simple airport db list)
1140 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1142 SGPath aptdb( globals->get_fg_root() );
1143 aptdb.append( "Airports/apt.dat" );
1145 SGPath p_metar( globals->get_fg_root() );
1146 p_metar.append( "Airports/metar.dat" );
1148 FGAirportList *airports = new FGAirportList();
1149 globals->set_airports( airports );
1151 fgAirportDBLoad( airports, aptdb.str(), p_metar.str() );
1153 FGNavList *navlist = new FGNavList;
1154 FGNavList *loclist = new FGNavList;
1155 FGNavList *gslist = new FGNavList;
1156 FGNavList *dmelist = new FGNavList;
1157 FGNavList *mkrlist = new FGNavList;
1158 FGNavList *tacanlist = new FGNavList;
1159 FGNavList *carrierlist = new FGNavList;
1160 FGTACANList *channellist = new FGTACANList;
1162 globals->set_navlist( navlist );
1163 globals->set_loclist( loclist );
1164 globals->set_gslist( gslist );
1165 globals->set_dmelist( dmelist );
1166 globals->set_mkrlist( mkrlist );
1167 globals->set_tacanlist( tacanlist );
1168 globals->set_carrierlist( carrierlist );
1169 globals->set_channellist( channellist );
1171 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1172 SG_LOG( SG_GENERAL, SG_ALERT,
1173 "Problems loading one or more navigational database" );
1176 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1177 // align all the localizers with their corresponding runways
1178 // since data sources are good for cockpit navigation
1179 // purposes, but not always to the error tolerances needed to
1180 // exactly place these items.
1182 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1184 fgNavDBAlignLOCwithRunway( airports, loclist, threshold );
1187 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1188 SGPath p_fix( globals->get_fg_root() );
1189 p_fix.append( "Navaids/fix.dat" );
1190 FGFixList *fixlist = new FGFixList;
1191 fixlist->init( p_fix );
1192 globals->set_fixlist( fixlist );
1194 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1195 SGPath p_awy( globals->get_fg_root() );
1196 p_awy.append( "Navaids/awy.dat" );
1197 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1198 //cerr << "Loading Airways" << endl;
1199 awyNet->load (p_awy );
1201 //cerr << "initializing airways" << endl;
1202 globals->set_airwaynet( awyNet );
1208 // Set the initial position based on presets (or defaults)
1209 bool fgInitPosition() {
1210 // cout << "fgInitPosition()" << endl;
1211 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1212 * SG_DEGREES_TO_RADIANS ;
1213 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1214 double alt = fgGetDouble("/sim/presets/altitude-ft");
1216 bool set_pos = false;
1218 // If glideslope is specified, then calculate offset-distance or
1219 // altitude relative to glide slope if either of those was not
1221 if ( fabs( gs ) > 0.01 ) {
1222 fgSetDistOrAltFromGlideSlope();
1226 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1227 // If not, check for an airport-id and use that.
1228 // If not, default to the middle of the KSFO field.
1229 // The default values for lon/lat are deliberately out of range
1230 // so that the airport-id can take effect; valid lon/lat will
1231 // override airport-id, however.
1232 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1233 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1234 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1235 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1240 string apt = fgGetString("/sim/presets/airport-id");
1241 string rwy_no = fgGetString("/sim/presets/runway");
1242 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1243 string vor = fgGetString("/sim/presets/vor-id");
1244 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1245 string ndb = fgGetString("/sim/presets/ndb-id");
1246 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1247 string carrier = fgGetString("/sim/presets/carrier");
1248 string parkpos = fgGetString("/sim/presets/parkpos");
1249 string fix = fgGetString("/sim/presets/fix");
1250 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1251 double hdg = hdg_preset->getDoubleValue();
1253 // save some start parameters, so that we can later say what the
1254 // user really requested. TODO generalize that and move it to options.cxx
1255 static bool start_options_saved = false;
1256 if (!start_options_saved) {
1257 start_options_saved = true;
1258 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1260 opt->setDoubleValue("latitude-deg", lat_deg);
1261 opt->setDoubleValue("longitude-deg", lon_deg);
1262 opt->setDoubleValue("heading-deg", hdg);
1263 opt->setStringValue("airport", apt.c_str());
1264 opt->setStringValue("runway", rwy_no.c_str());
1268 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1270 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1271 // An airport + parking position is requested
1272 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1273 // set tower position
1274 fgSetString("/sim/tower/airport-id", apt.c_str());
1279 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1280 // An airport + runway is requested
1281 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1282 // set tower position (a little off the heading for single
1284 fgSetString("/sim/tower/airport-id", apt.c_str());
1289 if ( !set_pos && !apt.empty() ) {
1290 // An airport is requested (find runway closest to hdg)
1291 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1292 // set tower position (a little off the heading for single
1294 fgSetString("/sim/tower/airport-id", apt.c_str());
1299 if (hdg_preset->getDoubleValue() > 9990.0)
1300 hdg_preset->setDoubleValue(hdg);
1302 if ( !set_pos && !vor.empty() ) {
1303 // a VOR is requested
1304 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1309 if ( !set_pos && !ndb.empty() ) {
1310 // an NDB is requested
1311 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1316 if ( !set_pos && !carrier.empty() ) {
1317 // an aircraft carrier is requested
1318 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1323 if ( !set_pos && !fix.empty() ) {
1324 // a Fix is requested
1325 if ( fgSetPosFromFix( fix ) ) {
1331 // No lon/lat specified, no airport specified, default to
1332 // middle of KSFO field.
1333 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1334 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1337 fgSetDouble( "/position/longitude-deg",
1338 fgGetDouble("/sim/presets/longitude-deg") );
1339 fgSetDouble( "/position/latitude-deg",
1340 fgGetDouble("/sim/presets/latitude-deg") );
1341 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1343 // determine if this should be an on-ground or in-air start
1344 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1345 fgSetBool("/sim/presets/onground", false);
1347 fgSetBool("/sim/presets/onground", true);
1354 // General house keeping initializations
1355 bool fgInitGeneral() {
1358 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1359 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1361 root = globals->get_fg_root();
1362 if ( ! root.length() ) {
1363 // No root path set? Then bail ...
1364 SG_LOG( SG_GENERAL, SG_ALERT,
1365 "Cannot continue without a path to the base package "
1366 << "being defined." );
1369 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1371 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1373 char buf[512], *cwd = getcwd(buf, 511);
1375 SGPropertyNode *curr = fgGetNode("/sim", true);
1376 curr->removeChild("fg-current", 0, false);
1377 curr = curr->getChild("fg-current", 0, true);
1378 curr->setStringValue(cwd ? cwd : "");
1379 curr->setAttribute(SGPropertyNode::WRITE, false);
1384 // Initialize the flight model subsystem. This just creates the
1385 // object. The actual fdm initialization is delayed until we get a
1386 // proper scenery elevation hit. This is checked for in main.cxx
1390 if ( cur_fdm_state ) {
1391 delete cur_fdm_state;
1395 double dt = 1.0 / fgGetInt("/sim/model-hz");
1396 string model = fgGetString("/sim/flight-model");
1398 if ( model == "larcsim" ) {
1399 cur_fdm_state = new FGLaRCsim( dt );
1400 } else if ( model == "jsb" ) {
1401 cur_fdm_state = new FGJSBsim( dt );
1403 } else if ( model == "ada" ) {
1404 cur_fdm_state = new FGADA( dt );
1405 } else if ( model == "acms" ) {
1406 cur_fdm_state = new FGACMS( dt );
1407 } else if ( model == "balloon" ) {
1408 cur_fdm_state = new FGBalloonSim( dt );
1409 } else if ( model == "magic" ) {
1410 cur_fdm_state = new FGMagicCarpet( dt );
1412 } else if ( model == "ufo" ) {
1413 cur_fdm_state = new FGUFO( dt );
1414 } else if ( model == "external" ) {
1415 // external is a synonym for "--fdm=null" and is
1416 // maintained here for backwards compatibility
1417 cur_fdm_state = new FGNullFDM( dt );
1418 } else if ( model.find("network") == 0 ) {
1419 string host = "localhost";
1423 string net_options = model.substr(8);
1424 string::size_type begin, end;
1427 end = net_options.find( ",", begin );
1428 if ( end != string::npos ) {
1429 host = net_options.substr(begin, end - begin);
1433 end = net_options.find( ",", begin );
1434 if ( end != string::npos ) {
1435 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1439 end = net_options.find( ",", begin );
1440 if ( end != string::npos ) {
1441 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1445 end = net_options.find( ",", begin );
1446 if ( end != string::npos ) {
1447 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1450 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1451 } else if ( model.find("pipe") == 0 ) {
1452 // /* old */ string pipe_path = model.substr(5);
1453 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1454 string pipe_path = "";
1455 string pipe_protocol = "";
1456 string pipe_options = model.substr(5);
1457 string::size_type begin, end;
1460 end = pipe_options.find( ",", begin );
1461 if ( end != string::npos ) {
1462 pipe_path = pipe_options.substr(begin, end - begin);
1465 // protocol (last option)
1466 pipe_protocol = pipe_options.substr(begin);
1467 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1468 } else if ( model == "null" ) {
1469 cur_fdm_state = new FGNullFDM( dt );
1470 } else if ( model == "yasim" ) {
1471 cur_fdm_state = new YASim( dt );
1473 throw sg_throwable(string("Unrecognized flight model '") + model
1474 + "', cannot init flight dynamics model.");
1478 // Initialize view parameters
1480 // force update of model so that viewer can get some data...
1481 globals->get_aircraft_model()->update(0);
1482 // run update for current view so that data is current...
1483 globals->get_viewmgr()->update(0);
1487 SGTime *fgInitTime() {
1489 static const SGPropertyNode *longitude
1490 = fgGetNode("/position/longitude-deg");
1491 static const SGPropertyNode *latitude
1492 = fgGetNode("/position/latitude-deg");
1493 static const SGPropertyNode *cur_time_override
1494 = fgGetNode("/sim/time/cur-time-override", true);
1496 SGPath zone( globals->get_fg_root() );
1497 zone.append( "Timezone" );
1498 SGTime *t = new SGTime( longitude->getDoubleValue()
1499 * SGD_DEGREES_TO_RADIANS,
1500 latitude->getDoubleValue()
1501 * SGD_DEGREES_TO_RADIANS,
1503 cur_time_override->getLongValue() );
1505 globals->set_warp_delta( 0 );
1507 t->update( 0.0, 0.0,
1508 cur_time_override->getLongValue(),
1509 globals->get_warp() );
1515 // set up a time offset (aka warp) if one is specified
1516 void fgInitTimeOffset() {
1517 static const SGPropertyNode *longitude
1518 = fgGetNode("/position/longitude-deg");
1519 static const SGPropertyNode *latitude
1520 = fgGetNode("/position/latitude-deg");
1521 static const SGPropertyNode *cur_time_override
1522 = fgGetNode("/sim/time/cur-time-override", true);
1524 // Handle potential user specified time offsets
1525 int orig_warp = globals->get_warp();
1526 SGTime *t = globals->get_time_params();
1527 time_t cur_time = t->get_cur_time();
1528 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1529 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1530 time_t aircraftLocalTime =
1531 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1533 // Okay, we now have several possible scenarios
1534 int offset = fgGetInt("/sim/startup/time-offset");
1535 string offset_type = fgGetString("/sim/startup/time-offset-type");
1538 if ( offset_type == "real" ) {
1540 } else if ( offset_type == "dawn" ) {
1541 warp = fgTimeSecondsUntilSunAngle( cur_time,
1542 longitude->getDoubleValue()
1543 * SGD_DEGREES_TO_RADIANS,
1544 latitude->getDoubleValue()
1545 * SGD_DEGREES_TO_RADIANS,
1547 } else if ( offset_type == "morning" ) {
1548 warp = fgTimeSecondsUntilSunAngle( cur_time,
1549 longitude->getDoubleValue()
1550 * SGD_DEGREES_TO_RADIANS,
1551 latitude->getDoubleValue()
1552 * SGD_DEGREES_TO_RADIANS,
1554 } else if ( offset_type == "noon" ) {
1555 warp = fgTimeSecondsUntilSunAngle( cur_time,
1556 longitude->getDoubleValue()
1557 * SGD_DEGREES_TO_RADIANS,
1558 latitude->getDoubleValue()
1559 * SGD_DEGREES_TO_RADIANS,
1561 } else if ( offset_type == "afternoon" ) {
1562 warp = fgTimeSecondsUntilSunAngle( cur_time,
1563 longitude->getDoubleValue()
1564 * SGD_DEGREES_TO_RADIANS,
1565 latitude->getDoubleValue()
1566 * SGD_DEGREES_TO_RADIANS,
1568 } else if ( offset_type == "dusk" ) {
1569 warp = fgTimeSecondsUntilSunAngle( cur_time,
1570 longitude->getDoubleValue()
1571 * SGD_DEGREES_TO_RADIANS,
1572 latitude->getDoubleValue()
1573 * SGD_DEGREES_TO_RADIANS,
1575 } else if ( offset_type == "evening" ) {
1576 warp = fgTimeSecondsUntilSunAngle( cur_time,
1577 longitude->getDoubleValue()
1578 * SGD_DEGREES_TO_RADIANS,
1579 latitude->getDoubleValue()
1580 * SGD_DEGREES_TO_RADIANS,
1582 } else if ( offset_type == "midnight" ) {
1583 warp = fgTimeSecondsUntilSunAngle( cur_time,
1584 longitude->getDoubleValue()
1585 * SGD_DEGREES_TO_RADIANS,
1586 latitude->getDoubleValue()
1587 * SGD_DEGREES_TO_RADIANS,
1589 } else if ( offset_type == "system-offset" ) {
1592 } else if ( offset_type == "gmt-offset" ) {
1593 warp = offset - (currGMT - systemLocalTime);
1595 } else if ( offset_type == "latitude-offset" ) {
1596 warp = offset - (aircraftLocalTime - systemLocalTime);
1598 } else if ( offset_type == "system" ) {
1599 warp = offset - (systemLocalTime - currGMT) - cur_time;
1600 } else if ( offset_type == "gmt" ) {
1601 warp = offset - cur_time;
1602 } else if ( offset_type == "latitude" ) {
1603 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1605 SG_LOG( SG_GENERAL, SG_ALERT,
1606 "FG_TIME::Unsupported offset type " << offset_type );
1609 globals->set_warp( orig_warp + warp );
1610 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1611 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1612 cur_time_override->getLongValue(),
1613 globals->get_warp() );
1615 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1616 << globals->get_warp() );
1620 // This is the top level init routine which calls all the other
1621 // initialization routines. If you are adding a subsystem to flight
1622 // gear, its initialization call should located in this routine.
1623 // Returns non-zero if a problem encountered.
1624 bool fgInitSubsystems() {
1625 // static const SGPropertyNode *longitude
1626 // = fgGetNode("/sim/presets/longitude-deg");
1627 // static const SGPropertyNode *latitude
1628 // = fgGetNode("/sim/presets/latitude-deg");
1629 // static const SGPropertyNode *altitude
1630 // = fgGetNode("/sim/presets/altitude-ft");
1631 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1632 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1634 ////////////////////////////////////////////////////////////////////
1635 // Initialize the event manager subsystem.
1636 ////////////////////////////////////////////////////////////////////
1638 globals->get_event_mgr()->init();
1639 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1641 ////////////////////////////////////////////////////////////////////
1642 // Initialize the property interpolator subsystem. Put into the INIT
1643 // group because the "nasal" subsystem may need it at GENERAL take-down.
1644 ////////////////////////////////////////////////////////////////////
1645 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1648 ////////////////////////////////////////////////////////////////////
1649 // Add the FlightGear property utilities.
1650 ////////////////////////////////////////////////////////////////////
1651 globals->add_subsystem("properties", new FGProperties);
1653 ////////////////////////////////////////////////////////////////////
1654 // Initialize the material property subsystem.
1655 ////////////////////////////////////////////////////////////////////
1657 SGPath mpath( globals->get_fg_root() );
1658 mpath.append( "materials.xml" );
1659 string season = fgGetString("/sim/startup/season", "summer");
1660 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1661 globals->get_props()) ) {
1662 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1667 ////////////////////////////////////////////////////////////////////
1668 // Initialize the scenery management subsystem.
1669 ////////////////////////////////////////////////////////////////////
1671 if ( globals->get_tile_mgr()->init() ) {
1672 // Load the local scenery data
1673 double visibility_meters = fgGetDouble("/environment/visibility-m");
1675 globals->get_tile_mgr()->update( visibility_meters );
1677 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1681 globals->get_scenery()->get_scene_graph()
1682 ->addChild(simgear::Particles::getCommonRoot());
1684 ////////////////////////////////////////////////////////////////////
1685 // Initialize the flight model subsystem.
1686 ////////////////////////////////////////////////////////////////////
1690 // allocates structures so must happen before any of the flight
1691 // model or control parameters are set
1692 fgAircraftInit(); // In the future this might not be the case.
1695 ////////////////////////////////////////////////////////////////////
1696 // Initialize the weather subsystem.
1697 ////////////////////////////////////////////////////////////////////
1699 // Initialize the weather modeling subsystem
1700 globals->add_subsystem("environment", new FGEnvironmentMgr);
1703 ////////////////////////////////////////////////////////////////////
1704 // Initialize the aircraft systems and instrumentation (before the
1706 ////////////////////////////////////////////////////////////////////
1708 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1709 globals->add_subsystem("systems", new FGSystemMgr);
1711 ////////////////////////////////////////////////////////////////////
1712 // Initialize the XML Autopilot subsystem.
1713 ////////////////////////////////////////////////////////////////////
1715 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1716 globals->add_subsystem( "route-manager", new FGRouteMgr );
1719 ////////////////////////////////////////////////////////////////////
1720 // Initialize the view manager subsystem.
1721 ////////////////////////////////////////////////////////////////////
1725 ////////////////////////////////////////////////////////////////////
1726 // Create and register the logger.
1727 ////////////////////////////////////////////////////////////////////
1729 globals->add_subsystem("logger", new FGLogger);
1731 ////////////////////////////////////////////////////////////////////
1732 // Create and register the XML GUI.
1733 ////////////////////////////////////////////////////////////////////
1735 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1738 ////////////////////////////////////////////////////////////////////
1739 // Initialize the local time subsystem.
1740 ////////////////////////////////////////////////////////////////////
1742 // update the current timezone each 30 minutes
1743 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1744 &fgUpdateLocalTime, 30*60 );
1745 fgInitTimeOffset(); // the environment subsystem needs this
1748 ////////////////////////////////////////////////////////////////////
1749 // Initialize the lighting subsystem.
1750 ////////////////////////////////////////////////////////////////////
1752 globals->add_subsystem("lighting", new FGLight);
1754 //////////////////////////////////////////////////////////////////////
1755 // Initialize the 2D cloud subsystem.
1756 ////////////////////////////////////////////////////////////////////
1757 fgGetBool("/sim/rendering/bump-mapping", false);
1759 #ifdef ENABLE_AUDIO_SUPPORT
1760 ////////////////////////////////////////////////////////////////////
1761 // Initialize the sound subsystem.
1762 ////////////////////////////////////////////////////////////////////
1764 init_volume = fgGetFloat("/sim/sound/volume");
1765 fgSetFloat("/sim/sound/volume", 0.0f);
1766 globals->set_soundmgr(new SGSoundMgr);
1767 globals->get_soundmgr()->init();
1768 globals->get_soundmgr()->bind();
1771 ////////////////////////////////////////////////////////////////////
1772 // Initialize the sound-effects subsystem.
1773 ////////////////////////////////////////////////////////////////////
1775 globals->add_subsystem("fx", new FGFX);
1776 globals->add_subsystem("voice", new FGVoiceMgr);
1779 ////////////////////////////////////////////////////////////////////
1780 // Initialise the ATC Manager
1781 ////////////////////////////////////////////////////////////////////
1783 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1784 globals->set_ATC_mgr(new FGATCMgr);
1785 globals->get_ATC_mgr()->init();
1787 ////////////////////////////////////////////////////////////////////
1788 // Initialise the AI Manager
1789 ////////////////////////////////////////////////////////////////////
1791 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1792 globals->set_AI_mgr(new FGAIMgr);
1793 globals->get_AI_mgr()->init();
1795 ////////////////////////////////////////////////////////////////////
1796 // Initialise the AI Model Manager
1797 ////////////////////////////////////////////////////////////////////
1798 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1799 globals->add_subsystem("ai_model", new FGAIManager);
1800 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1803 // It's probably a good idea to initialize the top level traffic manager
1804 // After the AI and ATC systems have been initialized properly.
1805 // AI Traffic manager
1806 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1809 ////////////////////////////////////////////////////////////////////
1810 // Initialize the cockpit subsystem
1811 ////////////////////////////////////////////////////////////////////
1812 if( fgCockpitInit( ¤t_aircraft )) {
1813 // Cockpit initialized ok.
1815 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1820 ////////////////////////////////////////////////////////////////////
1821 // Initialize I/O subsystem.
1822 ////////////////////////////////////////////////////////////////////
1824 globals->get_io()->init();
1825 globals->get_io()->bind();
1828 ////////////////////////////////////////////////////////////////////
1829 // Add a new 2D panel.
1830 ////////////////////////////////////////////////////////////////////
1832 string panel_path = fgGetString("/sim/panel/path",
1833 "Panels/Default/default.xml");
1835 globals->set_current_panel( fgReadPanel(panel_path) );
1836 if (globals->get_current_panel() == 0) {
1837 SG_LOG( SG_INPUT, SG_ALERT,
1838 "Error reading new panel from " << panel_path );
1840 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1841 globals->get_current_panel()->init();
1842 globals->get_current_panel()->bind();
1846 ////////////////////////////////////////////////////////////////////
1847 // Initialize the controls subsystem.
1848 ////////////////////////////////////////////////////////////////////
1850 globals->get_controls()->init();
1851 globals->get_controls()->bind();
1854 ////////////////////////////////////////////////////////////////////
1855 // Initialize the input subsystem.
1856 ////////////////////////////////////////////////////////////////////
1858 globals->add_subsystem("input", new FGInput);
1861 ////////////////////////////////////////////////////////////////////
1862 // Initialize the replay subsystem
1863 ////////////////////////////////////////////////////////////////////
1864 globals->add_subsystem("replay", new FGReplay);
1866 ////////////////////////////////////////////////////////////////////
1867 // Bind and initialize subsystems.
1868 ////////////////////////////////////////////////////////////////////
1870 globals->get_subsystem_mgr()->bind();
1871 globals->get_subsystem_mgr()->init();
1873 ////////////////////////////////////////////////////////////////////
1874 // Initialize multiplayer subsystem
1875 ////////////////////////////////////////////////////////////////////
1877 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1878 globals->get_multiplayer_mgr()->init();
1880 ////////////////////////////////////////////////////////////////////////
1881 // Initialize the Nasal interpreter.
1882 // Do this last, so that the loaded scripts see initialized state
1883 ////////////////////////////////////////////////////////////////////////
1884 FGNasalSys* nasal = new FGNasalSys();
1885 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1888 // initialize methods that depend on other subsystems.
1889 globals->get_subsystem_mgr()->postinit();
1891 ////////////////////////////////////////////////////////////////////////
1892 // End of subsystem initialization.
1893 ////////////////////////////////////////////////////////////////////
1895 SG_LOG( SG_GENERAL, SG_INFO, endl);
1897 // Save the initial state for future
1899 globals->saveInitialState();
1905 void fgReInitSubsystems()
1907 // static const SGPropertyNode *longitude
1908 // = fgGetNode("/sim/presets/longitude-deg");
1909 // static const SGPropertyNode *latitude
1910 // = fgGetNode("/sim/presets/latitude-deg");
1911 static const SGPropertyNode *altitude
1912 = fgGetNode("/sim/presets/altitude-ft");
1913 static const SGPropertyNode *master_freeze
1914 = fgGetNode("/sim/freeze/master");
1916 SG_LOG( SG_GENERAL, SG_INFO,
1917 "fgReInitSubsystems(): /position/altitude = "
1918 << altitude->getDoubleValue() );
1920 bool freeze = master_freeze->getBoolValue();
1922 fgSetBool("/sim/freeze/master", true);
1924 fgSetBool("/sim/crashed", false);
1926 // Force reupdating the positions of the ai 3d models. They are used for
1927 // initializing ground level for the FDM.
1928 globals->get_subsystem("ai_model")->reinit();
1930 // Initialize the FDM
1933 // allocates structures so must happen before any of the flight
1934 // model or control parameters are set
1935 fgAircraftInit(); // In the future this might not be the case.
1937 // reload offsets from config defaults
1938 globals->get_viewmgr()->reinit();
1942 globals->get_controls()->reset_all();
1944 fgUpdateLocalTime();
1946 // re-init to proper time of day setting
1950 fgSetBool("/sim/freeze/master", false);
1952 fgSetBool("/sim/sceneryloaded",false);
1956 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1958 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1960 bool freeze = master_freeze->getBoolValue();
1962 master_freeze->setBoolValue(true);
1964 fgSetBool("/sim/signals/reinit", true);
1965 cur_fdm_state->unbind();
1967 // in case user has changed window size as
1968 // restoreInitialState() overwrites these
1969 int xsize = fgGetInt("/sim/startup/xsize");
1970 int ysize = fgGetInt("/sim/startup/ysize");
1972 globals->restoreInitialState();
1974 // update our position based on current presets
1977 // We don't know how to resize the window, so keep the last values
1978 // for xsize and ysize, and don't use the one set initially
1979 fgSetInt("/sim/startup/xsize", xsize);
1980 fgSetInt("/sim/startup/ysize", ysize);
1982 SGTime *t = globals->get_time_params();
1985 globals->set_time_params(t);
1987 fgReInitSubsystems();
1989 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1990 globals->get_renderer()->resize(xsize, ysize);
1991 fgSetBool("/sim/signals/reinit", false);
1994 master_freeze->setBoolValue(false);