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/replay.hxx>
66 #include <Airports/apt_loader.hxx>
67 #include <Airports/runways.hxx>
68 #include <Airports/simple.hxx>
69 #include <AIModel/AIManager.hxx>
70 #include <ATCDCL/ATCmgr.hxx>
71 #include <ATCDCL/AIMgr.hxx>
72 #include <Autopilot/route_mgr.hxx>
73 #include <Autopilot/xmlauto.hxx>
74 #include <Cockpit/cockpit.hxx>
75 #include <Cockpit/panel.hxx>
76 #include <Cockpit/panel_io.hxx>
78 #include <FDM/SP/ADA.hxx>
79 #include <FDM/SP/ACMS.hxx>
80 #include <FDM/SP/MagicCarpet.hxx>
81 #include <FDM/SP/Balloon.h>
83 #include <FDM/ExternalNet/ExternalNet.hxx>
84 #include <FDM/ExternalPipe/ExternalPipe.hxx>
85 #include <FDM/JSBSim/JSBSim.hxx>
86 #include <FDM/LaRCsim/LaRCsim.hxx>
87 #include <FDM/UFO.hxx>
88 #include <FDM/NullFDM.hxx>
89 #include <FDM/YASim/YASim.hxx>
90 #include <GUI/new_gui.hxx>
91 #include <Include/general.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <AIModel/submodel.hxx>
96 #include <AIModel/AIManager.hxx>
97 #include <Navaids/navdb.hxx>
98 #include <Navaids/navlist.hxx>
99 #include <Scenery/scenery.hxx>
100 #include <Scenery/tilemgr.hxx>
101 #include <Scripting/NasalSys.hxx>
102 #include <Sound/fg_fx.hxx>
103 #include <Sound/beacon.hxx>
104 #include <Sound/morse.hxx>
105 #include <Sound/voice.hxx>
106 #include <Systems/system_mgr.hxx>
107 #include <Time/light.hxx>
108 #include <Time/sunsolver.hxx>
109 #include <Time/tmp.hxx>
110 #include <Traffic/TrafficMgr.hxx>
111 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <Environment/environment_mgr.hxx>
115 #include "fg_init.hxx"
117 #include "fg_commands.hxx"
118 #include "fg_props.hxx"
119 #include "options.hxx"
120 #include "globals.hxx"
121 #include "logger.hxx"
122 #include "renderer.hxx"
123 #include "viewmgr.hxx"
127 # include <CoreFoundation/CoreFoundation.h>
133 extern const char *default_root;
137 // Scan the command line options for the specified option and return
139 static string fgScanForOption( const string& option, int argc, char **argv ) {
142 if (hostname == NULL)
145 gethostname(_hostname, 256);
146 hostname = strdup(_hostname);
147 free_hostname = true;
150 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
152 int len = option.length();
155 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
157 string arg = argv[i];
158 if ( arg.find( option ) == 0 ) {
159 return arg.substr( len );
169 // Scan the user config files for the specified option and return
171 static string fgScanForOption( const string& option, const string& path ) {
172 sg_gzifstream in( path );
173 if ( !in.is_open() ) {
177 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
179 int len = option.length();
182 while ( ! in.eof() ) {
184 getline( in, line, '\n' );
186 // catch extraneous (DOS) line ending character
187 if ( line[line.length() - 1] < 32 ) {
188 line = line.substr( 0, line.length()-1 );
191 if ( line.find( option ) == 0 ) {
192 return line.substr( len );
201 // Scan the user config files for the specified option and return
203 static string fgScanForOption( const string& option ) {
206 #if defined( unix ) || defined( __CYGWIN__ )
207 // Next check home directory for .fgfsrc.hostname file
209 if ( homedir != NULL ) {
210 SGPath config( homedir );
211 config.append( ".fgfsrc" );
212 config.concat( "." );
213 config.concat( hostname );
214 arg = fgScanForOption( option, config.str() );
219 // Next check home directory for .fgfsrc file
221 if ( homedir != NULL ) {
222 SGPath config( homedir );
223 config.append( ".fgfsrc" );
224 arg = fgScanForOption( option, config.str() );
229 // Check for $fg_root/system.fgfsrc
230 SGPath config( globals->get_fg_root() );
231 config.append( "system.fgfsrc" );
232 arg = fgScanForOption( option, config.str() );
239 // Read in configuration (files and command line options) but only set
241 bool fgInitFGRoot ( int argc, char **argv ) {
244 // First parse command line options looking for --fg-root=, this
245 // will override anything specified in a config file
246 root = fgScanForOption( "--fg-root=", argc, argv);
248 // Check in one of the user configuration files.
250 root = fgScanForOption( "--fg-root=" );
252 // Next check if fg-root is set as an env variable
253 if ( root.empty() ) {
254 char *envp = ::getenv( "FG_ROOT" );
255 if ( envp != NULL ) {
260 // Otherwise, default to a random compiled-in location if we can't
261 // find fg-root any other way.
262 if ( root.empty() ) {
263 #if defined( __CYGWIN__ )
264 root = "/FlightGear";
265 #elif defined( WIN32 )
266 root = "\\FlightGear";
267 #elif defined(__APPLE__)
269 The following code looks for the base package inside the application
270 bundle, in the standard Contents/Resources location.
272 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
274 // look for a 'data' subdir
275 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
277 // now convert down to a path, and the a c-string
278 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
279 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
281 CFRelease(resourcesUrl);
289 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
290 globals->set_fg_root(root);
296 // Read in configuration (files and command line options) but only set
298 bool fgInitFGAircraft ( int argc, char **argv ) {
301 // First parse command line options looking for --aircraft=, this
302 // will override anything specified in a config file
303 aircraft = fgScanForOption( "--aircraft=", argc, argv );
304 if ( aircraft.empty() ) {
305 // check synonym option
306 aircraft = fgScanForOption( "--vehicle=", argc, argv );
309 // Check in one of the user configuration files.
310 if ( aircraft.empty() ) {
311 aircraft = fgScanForOption( "--aircraft=" );
313 if ( aircraft.empty() ) {
314 aircraft = fgScanForOption( "--vehicle=" );
317 // if an aircraft was specified, set the property name
318 if ( !aircraft.empty() ) {
319 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
320 fgSetString("/sim/aircraft", aircraft.c_str() );
322 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
329 // Return the current base package version
330 string fgBasePackageVersion() {
331 SGPath base_path( globals->get_fg_root() );
332 base_path.append("version");
334 sg_gzifstream in( base_path.str() );
335 if ( !in.is_open() ) {
336 SGPath old_path( globals->get_fg_root() );
337 old_path.append( "Thanks" );
338 sg_gzifstream old( old_path.str() );
339 if ( !old.is_open() ) {
342 return "[old version]";
353 // Initialize the localization
354 SGPropertyNode *fgInitLocale(const char *language) {
355 SGPropertyNode *c_node = NULL, *d_node = NULL;
356 SGPropertyNode *intl = fgGetNode("/sim/intl");
358 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
360 // localization not defined
365 // Select the proper language from the list
367 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
368 for (unsigned int i = 0; i < locale.size(); i++) {
370 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
371 for (unsigned int j = 0; j < lang.size(); j++) {
373 if (!strcmp(lang[j]->getStringValue(), language)) {
382 d_node = intl->getChild("locale");
386 // Check for localized font
387 SGPropertyNode *font_n = c_node->getNode("font", true);
388 if ( !strcmp(font_n->getStringValue(), "") )
389 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
393 // Load the default strings
395 SGPath d_path( globals->get_fg_root() );
397 const char *d_path_str = d_node->getStringValue("strings");
399 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
403 d_path.append(d_path_str);
404 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
406 SGPropertyNode *strings = c_node->getNode("strings");
408 readProperties(d_path.str(), strings);
409 } catch (const sg_exception &) {
410 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
415 // Load the language specific strings
417 if (c_node != d_node) {
418 SGPath c_path( globals->get_fg_root() );
420 const char *c_path_str = c_node->getStringValue("strings");
422 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
426 c_path.append(c_path_str);
427 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
430 readProperties(c_path.str(), strings);
431 } catch (const sg_exception &) {
432 SG_LOG(SG_GENERAL, SG_ALERT,
433 "Unable to read the localized strings from " << c_path.str());
443 // Initialize the localization routines
444 bool fgDetectLanguage() {
445 const char *language = ::getenv("LANG");
447 if (language == NULL) {
448 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
452 SGPropertyNode *locale = fgInitLocale(language);
454 SG_LOG(SG_GENERAL, SG_ALERT,
455 "No internationalization settings specified in preferences.xml" );
460 globals->set_locale( locale );
465 // Attempt to locate and parse the various non-XML config files in order
466 // from least precidence to greatest precidence
468 do_options (int argc, char ** argv)
470 // Check for $fg_root/system.fgfsrc
471 SGPath config( globals->get_fg_root() );
472 config.append( "system.fgfsrc" );
473 fgParseOptions(config.str());
475 #if defined( unix ) || defined( __CYGWIN__ )
476 config.concat( "." );
477 config.concat( hostname );
478 fgParseOptions(config.str());
481 // Check for ~/.fgfsrc
482 if ( homedir != NULL ) {
483 config.set( homedir );
484 config.append( ".fgfsrc" );
485 fgParseOptions(config.str());
488 #if defined( unix ) || defined( __CYGWIN__ )
489 // Check for ~/.fgfsrc.hostname
490 config.concat( "." );
491 config.concat( hostname );
492 fgParseOptions(config.str());
495 // Parse remaining command line options
496 // These will override anything specified in a config file
497 fgParseArgs(argc, argv);
501 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
502 SGPropertyNode *cache, int depth = 0 )
504 const int MAXDEPTH = 1;
507 ulDir *dirp = ulOpenDir(path.str().c_str());
509 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
514 while ((dire = ulReadDir(dirp)) != NULL) {
516 if (depth > MAXDEPTH)
519 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
520 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
524 next.append(dire->d_name);
526 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
527 if ( ! result.empty() )
531 int len = strlen(dire->d_name);
532 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
538 if (!cache->getChild("aircraft", i++, false))
541 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
543 n = entry->getNode("file", true);
544 n->setStringValue(dire->d_name);
545 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
547 n = entry->getNode("path", true);
548 n->setStringValue(path.str().c_str());
549 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
551 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
563 // Read in configuration (file and command line)
564 bool fgInitConfig ( int argc, char **argv ) {
566 // First, set some sane default values
569 // Read global preferences from $FG_ROOT/preferences.xml
570 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
571 fgLoadProps("preferences.xml", globals->get_props());
572 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
574 // Detect the required language as early as possible
575 if ( !fgDetectLanguage() ) {
579 SGPropertyNode autosave;
581 char *envp = ::getenv( "APPDATA" );
583 SGPath config( envp );
584 config.append( "flightgear.org" );
586 if ( homedir != NULL ) {
587 SGPath config( homedir );
588 config.append( ".fgfs" );
590 const char *fg_home = getenv("FG_HOME");
594 // Set /sim/fg-home and don't allow malign code to override it until
595 // Nasal security is set up. Use FG_HOME if necessary.
596 SGPropertyNode *home = fgGetNode("/sim", true);
597 home->removeChild("fg-home", 0, false);
598 home = home->getChild("fg-home", 0, true);
599 home->setStringValue(config.c_str());
600 home->setAttribute(SGPropertyNode::WRITE, false);
602 config.append( "autosave.xml" );
603 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
605 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
607 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
609 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
611 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
614 // Scan user config files and command line for a specified aircraft.
615 fgInitFGAircraft(argc, argv);
617 string aircraft = fgGetString( "/sim/aircraft", "" );
618 if ( aircraft.size() > 0 ) {
619 SGPath aircraft_search( globals->get_fg_root() );
620 aircraft_search.append( "Aircraft" );
622 string aircraft_set = aircraft + "-set.xml";
625 // check if the *-set.xml file is already in the cache
626 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
627 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
628 for (unsigned int i = 0; i < cache.size(); i++) {
629 const char *name = cache[i]->getStringValue("file", "");
630 if (aircraft_set == name) {
631 const char *path = cache[i]->getStringValue("path", "");
641 if (result.empty()) {
642 // prepare cache for rescan
643 SGPropertyNode *n = cache_root->getNode("fg-root", true);
644 n->setStringValue(globals->get_fg_root().c_str());
645 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
646 cache_root->removeChildren("aircraft");
648 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
651 if ( !result.empty() ) {
652 fgSetString( "/sim/aircraft-dir", result.c_str() );
653 SGPath full_name( result );
654 full_name.append( aircraft_set );
656 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
657 << " from " << full_name.str());
659 readProperties( full_name.str(), globals->get_props() );
660 } catch ( const sg_exception &e ) {
661 string message = "Error reading default aircraft: ";
662 message += e.getFormattedMessage();
663 SG_LOG(SG_INPUT, SG_ALERT, message);
667 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
673 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
676 copyProperties(&autosave, globals->get_props());
678 // parse options after loading aircraft to ensure any user
679 // overrides of defaults are honored.
680 do_options(argc, argv);
691 // This function is never used, but maybe useful in the future ???
694 // Preset lon/lat given an airport id
695 static bool fgSetPosFromAirportID( const string& id ) {
699 SG_LOG( SG_GENERAL, SG_INFO,
700 "Attempting to set starting position from airport code " << id );
702 if ( fgFindAirportID( id, &a ) ) {
704 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
705 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
707 // other code depends on the actual postition being set so set
709 fgSetDouble("/position/longitude-deg", a->longitude );
710 fgSetDouble("/position/latitude-deg", a->latitude );
712 SG_LOG( SG_GENERAL, SG_INFO,
713 "Position for " << id << " is (" << a->longitude
714 << ", " << a->latitude << ")" );
724 // Set current tower position lon/lat given an airport id
725 static bool fgSetTowerPosFromAirportID( const string& id) {
726 const FGAirport *a = fgFindAirportID( id);
728 SGGeod tower = a->getTowerLocation();
729 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
730 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
731 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
739 struct FGTowerLocationListener : SGPropertyChangeListener {
740 void valueChanged(SGPropertyNode* node) {
741 const string id(node->getStringValue());
742 fgSetTowerPosFromAirportID(id);
746 void fgInitTowerLocationListener() {
747 fgGetNode("/sim/tower/airport-id", true)
748 ->addChangeListener( new FGTowerLocationListener(), true );
751 // Set current_options lon/lat given an airport id and heading (degrees)
752 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
758 // set initial position from runway and heading
759 SG_LOG( SG_GENERAL, SG_INFO,
760 "Attempting to set starting position from airport code "
761 << id << " heading " << tgt_hdg );
763 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
764 SG_LOG( SG_GENERAL, SG_ALERT,
765 "Failed to find a good runway for " << id << '\n' );
768 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
770 double lat2, lon2, az2;
771 double heading = r._heading;
772 double azimuth = heading + 180.0;
773 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
775 SG_LOG( SG_GENERAL, SG_INFO,
776 "runway = " << r._lon << ", " << r._lat
777 << " length = " << r._length * SG_FEET_TO_METER
778 << " heading = " << azimuth );
780 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
781 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
782 &lat2, &lon2, &az2 );
784 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
786 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
787 odist *= SG_NM_TO_METER;
788 double oaz = azimuth;
789 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
790 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
793 while ( oaz >= 360.0 ) { oaz -= 360.0; }
794 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
800 fgSetDouble("/sim/presets/longitude-deg", lon2 );
801 fgSetDouble("/sim/presets/latitude-deg", lat2 );
802 fgSetDouble("/sim/presets/heading-deg", heading );
804 // other code depends on the actual values being set ...
805 fgSetDouble("/position/longitude-deg", lon2 );
806 fgSetDouble("/position/latitude-deg", lat2 );
807 fgSetDouble("/orientation/heading-deg", heading );
809 SG_LOG( SG_GENERAL, SG_INFO,
810 "Position for " << id << " is ("
812 << lat2 << ") new heading is "
818 // Set current_options lon/lat given an airport id and parkig position name
819 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
823 // can't see an easy way around this const_cast at the moment
824 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
826 SG_LOG( SG_GENERAL, SG_ALERT,
827 "Failed to find airport " << id );
830 FGAirportDynamics* dcs = apt->getDynamics();
832 SG_LOG( SG_GENERAL, SG_ALERT,
833 "Failed to find parking position " << parkpos <<
834 " at airport " << id );
838 int park_index = dcs->getNrOfParkings() - 1;
839 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
840 if (park_index < 0) {
841 SG_LOG( SG_GENERAL, SG_ALERT,
842 "Failed to find parking position " << parkpos <<
843 " at airport " << id );
846 FGParking* parking = dcs->getParking(park_index);
848 double lat = parking->getLatitude();
849 double lon = parking->getLongitude();
850 double hdg = parking->getHeading();
853 fgSetDouble("/sim/presets/longitude-deg", lon );
854 fgSetDouble("/sim/presets/latitude-deg", lat );
855 fgSetDouble("/sim/presets/heading-deg", hdg );
857 // other code depends on the actual values being set ...
858 fgSetDouble("/position/longitude-deg", lon );
859 fgSetDouble("/position/latitude-deg", lat );
860 fgSetDouble("/orientation/heading-deg", hdg );
862 SG_LOG( SG_GENERAL, SG_INFO,
863 "Position for " << id << " is ("
865 << lat << ") new heading is "
872 // Set current_options lon/lat given an airport id and runway number
873 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
879 // set initial position from airport and runway number
880 SG_LOG( SG_GENERAL, SG_INFO,
881 "Attempting to set starting position for "
882 << id << ":" << rwy );
884 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
885 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
886 "Failed to find runway " << rwy <<
887 " at airport " << id << ". Using default runway." );
890 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
892 double lat2, lon2, az2;
893 double heading = r._heading;
894 double azimuth = heading + 180.0;
895 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
897 SG_LOG( SG_GENERAL, SG_INFO,
898 "runway = " << r._lon << ", " << r._lat
899 << " length = " << r._length * SG_FEET_TO_METER
900 << " heading = " << azimuth );
902 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
903 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
904 &lat2, &lon2, &az2 );
906 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
909 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
910 odist *= SG_NM_TO_METER;
911 double oaz = azimuth;
912 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
914 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
915 heading = fgGetDouble("/sim/presets/heading-deg");
917 while ( oaz >= 360.0 ) { oaz -= 360.0; }
918 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
924 fgSetDouble("/sim/presets/longitude-deg", lon2 );
925 fgSetDouble("/sim/presets/latitude-deg", lat2 );
926 fgSetDouble("/sim/presets/heading-deg", heading );
928 // other code depends on the actual values being set ...
929 fgSetDouble("/position/longitude-deg", lon2 );
930 fgSetDouble("/position/latitude-deg", lat2 );
931 fgSetDouble("/orientation/heading-deg", heading );
933 SG_LOG( SG_GENERAL, SG_INFO,
934 "Position for " << id << " is ("
936 << lat2 << ") new heading is "
943 static void fgSetDistOrAltFromGlideSlope() {
944 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
945 string apt_id = fgGetString("/sim/presets/airport-id");
946 double gs = fgGetDouble("/sim/presets/glideslope-deg")
947 * SG_DEGREES_TO_RADIANS ;
948 double od = fgGetDouble("/sim/presets/offset-distance-nm");
949 double alt = fgGetDouble("/sim/presets/altitude-ft");
951 double apt_elev = 0.0;
952 if ( ! apt_id.empty() ) {
953 apt_elev = fgGetAirportElev( apt_id );
954 if ( apt_elev < -9990.0 ) {
961 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
962 // set altitude from glideslope and offset-distance
963 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
964 alt = fabs(od*tan(gs)) + apt_elev;
965 fgSetDouble("/sim/presets/altitude-ft", alt);
966 fgSetBool("/sim/presets/onground", false);
967 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
969 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
970 // set offset-distance from glideslope and altitude
971 od = (alt - apt_elev) / tan(gs);
972 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
973 fgSetDouble("/sim/presets/offset-distance-nm", od);
974 fgSetBool("/sim/presets/onground", false);
975 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
977 } else if( fabs(gs) > 0.01 ) {
978 SG_LOG( SG_GENERAL, SG_ALERT,
979 "Glideslope given but not altitude or offset-distance." );
980 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
981 fgSetDouble("/sim/presets/glideslope-deg", 0);
982 fgSetBool("/sim/presets/onground", true);
987 // Set current_options lon/lat given an airport id and heading (degrees)
988 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
990 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
992 // set initial position from runway and heading
994 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
995 << id << ":" << freq );
997 double lon = nav->get_lon();
998 double lat = nav->get_lat();
1000 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1002 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1004 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1006 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1007 double olat, olon, az2;
1008 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1015 fgSetDouble("/sim/presets/longitude-deg", lon );
1016 fgSetDouble("/sim/presets/latitude-deg", lat );
1018 // other code depends on the actual values being set ...
1019 fgSetDouble("/position/longitude-deg", lon );
1020 fgSetDouble("/position/latitude-deg", lat );
1021 fgSetDouble("/orientation/heading-deg",
1022 fgGetDouble("/sim/presets/heading-deg") );
1024 SG_LOG( SG_GENERAL, SG_INFO,
1025 "Position for " << id << ":" << freq << " is ("
1026 << lon << ", "<< lat << ")" );
1030 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1031 << id << ":" << freq );
1036 // Set current_options lon/lat given an aircraft carrier id
1037 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1039 // set initial position from runway and heading
1043 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1044 double lon = geodPos.getLongitudeDeg();
1045 double lat = geodPos.getLatitudeDeg();
1046 double alt = geodPos.getElevationFt();
1048 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1049 << carrier << " at lat = " << lat << ", lon = " << lon
1050 << ", alt = " << alt << ", heading = " << heading);
1052 fgSetDouble("/sim/presets/longitude-deg", lon);
1053 fgSetDouble("/sim/presets/latitude-deg", lat);
1054 fgSetDouble("/sim/presets/altitude-ft", alt);
1055 fgSetDouble("/sim/presets/heading-deg", heading);
1056 fgSetDouble("/position/longitude-deg", lon);
1057 fgSetDouble("/position/latitude-deg", lat);
1058 fgSetDouble("/position/altitude-ft", alt);
1059 fgSetDouble("/orientation/heading-deg", heading);
1061 fgSetString("/sim/presets/speed-set", "UVW");
1062 fgSetDouble("/velocities/uBody-fps", uvw(0));
1063 fgSetDouble("/velocities/vBody-fps", uvw(1));
1064 fgSetDouble("/velocities/wBody-fps", uvw(2));
1065 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1066 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1067 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1069 fgSetBool("/sim/presets/onground", true);
1073 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1079 // Set current_options lon/lat given an airport id and heading (degrees)
1080 static bool fgSetPosFromFix( const string& id ) {
1083 // set initial position from runway and heading
1084 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1085 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1088 double lon = fix.get_lon();
1089 double lat = fix.get_lat();
1091 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1093 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1095 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1097 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1098 double olat, olon, az2;
1099 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1106 fgSetDouble("/sim/presets/longitude-deg", lon );
1107 fgSetDouble("/sim/presets/latitude-deg", lat );
1109 // other code depends on the actual values being set ...
1110 fgSetDouble("/position/longitude-deg", lon );
1111 fgSetDouble("/position/latitude-deg", lat );
1112 fgSetDouble("/orientation/heading-deg",
1113 fgGetDouble("/sim/presets/heading-deg") );
1115 SG_LOG( SG_GENERAL, SG_INFO,
1116 "Position for " << id << " is ("
1117 << lon << ", "<< lat << ")" );
1121 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1129 * Initialize vor/ndb/ils/fix list management and query systems (as
1130 * well as simple airport db list)
1135 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1137 SGPath aptdb( globals->get_fg_root() );
1138 aptdb.append( "Airports/apt.dat" );
1140 SGPath p_metar( globals->get_fg_root() );
1141 p_metar.append( "Airports/metar.dat" );
1143 FGAirportList *airports = new FGAirportList();
1144 globals->set_airports( airports );
1145 FGRunwayList *runways = new FGRunwayList();
1146 globals->set_runways( runways );
1148 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1150 FGNavList *navlist = new FGNavList;
1151 FGNavList *loclist = new FGNavList;
1152 FGNavList *gslist = new FGNavList;
1153 FGNavList *dmelist = new FGNavList;
1154 FGNavList *mkrlist = new FGNavList;
1155 FGNavList *tacanlist = new FGNavList;
1156 FGNavList *carrierlist = new FGNavList;
1157 FGTACANList *channellist = new FGTACANList;
1159 globals->set_navlist( navlist );
1160 globals->set_loclist( loclist );
1161 globals->set_gslist( gslist );
1162 globals->set_dmelist( dmelist );
1163 globals->set_mkrlist( mkrlist );
1164 globals->set_tacanlist( tacanlist );
1165 globals->set_carrierlist( carrierlist );
1166 globals->set_channellist( channellist );
1168 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1169 SG_LOG( SG_GENERAL, SG_ALERT,
1170 "Problems loading one or more navigational database" );
1173 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1174 // align all the localizers with their corresponding runways
1175 // since data sources are good for cockpit navigation
1176 // purposes, but not always to the error tolerances needed to
1177 // exactly place these items.
1179 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1181 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1184 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1185 SGPath p_fix( globals->get_fg_root() );
1186 p_fix.append( "Navaids/fix.dat" );
1187 FGFixList *fixlist = new FGFixList;
1188 fixlist->init( p_fix );
1189 globals->set_fixlist( fixlist );
1191 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1192 SGPath p_awy( globals->get_fg_root() );
1193 p_awy.append( "Navaids/awy.dat" );
1194 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1195 //cerr << "Loading Airways" << endl;
1196 awyNet->load (p_awy );
1198 //cerr << "initializing airways" << endl;
1199 globals->set_airwaynet( awyNet );
1205 // Set the initial position based on presets (or defaults)
1206 bool fgInitPosition() {
1207 // cout << "fgInitPosition()" << endl;
1208 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1209 * SG_DEGREES_TO_RADIANS ;
1210 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1211 double alt = fgGetDouble("/sim/presets/altitude-ft");
1213 bool set_pos = false;
1215 // If glideslope is specified, then calculate offset-distance or
1216 // altitude relative to glide slope if either of those was not
1218 if ( fabs( gs ) > 0.01 ) {
1219 fgSetDistOrAltFromGlideSlope();
1223 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1224 // If not, check for an airport-id and use that.
1225 // If not, default to the middle of the KSFO field.
1226 // The default values for lon/lat are deliberately out of range
1227 // so that the airport-id can take effect; valid lon/lat will
1228 // override airport-id, however.
1229 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1230 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1231 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1232 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1237 string apt = fgGetString("/sim/presets/airport-id");
1238 string rwy_no = fgGetString("/sim/presets/runway");
1239 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1240 string vor = fgGetString("/sim/presets/vor-id");
1241 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1242 string ndb = fgGetString("/sim/presets/ndb-id");
1243 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1244 string carrier = fgGetString("/sim/presets/carrier");
1245 string parkpos = fgGetString("/sim/presets/parkpos");
1246 string fix = fgGetString("/sim/presets/fix");
1247 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1248 double hdg = hdg_preset->getDoubleValue();
1250 // save some start parameters, so that we can later say what the
1251 // user really requested. TODO generalize that and move it to options.cxx
1252 static bool start_options_saved = false;
1253 if (!start_options_saved) {
1254 start_options_saved = true;
1255 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1257 opt->setDoubleValue("latitude-deg", lat_deg);
1258 opt->setDoubleValue("longitude-deg", lon_deg);
1259 opt->setDoubleValue("heading-deg", hdg);
1260 opt->setStringValue("airport", apt.c_str());
1261 opt->setStringValue("runway", rwy_no.c_str());
1265 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1267 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1268 // An airport + parking position is requested
1269 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1270 // set tower position
1271 fgSetString("/sim/tower/airport-id", apt.c_str());
1276 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1277 // An airport + runway is requested
1278 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1279 // set tower position (a little off the heading for single
1281 fgSetString("/sim/tower/airport-id", apt.c_str());
1286 if ( !set_pos && !apt.empty() ) {
1287 // An airport is requested (find runway closest to hdg)
1288 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1289 // set tower position (a little off the heading for single
1291 fgSetString("/sim/tower/airport-id", apt.c_str());
1296 if (hdg_preset->getDoubleValue() > 9990.0)
1297 hdg_preset->setDoubleValue(hdg);
1299 if ( !set_pos && !vor.empty() ) {
1300 // a VOR is requested
1301 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1306 if ( !set_pos && !ndb.empty() ) {
1307 // an NDB is requested
1308 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1313 if ( !set_pos && !carrier.empty() ) {
1314 // an aircraft carrier is requested
1315 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1320 if ( !set_pos && !fix.empty() ) {
1321 // a Fix is requested
1322 if ( fgSetPosFromFix( fix ) ) {
1328 // No lon/lat specified, no airport specified, default to
1329 // middle of KSFO field.
1330 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1331 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1334 fgSetDouble( "/position/longitude-deg",
1335 fgGetDouble("/sim/presets/longitude-deg") );
1336 fgSetDouble( "/position/latitude-deg",
1337 fgGetDouble("/sim/presets/latitude-deg") );
1338 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1340 // determine if this should be an on-ground or in-air start
1341 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1342 fgSetBool("/sim/presets/onground", false);
1344 fgSetBool("/sim/presets/onground", true);
1351 // General house keeping initializations
1352 bool fgInitGeneral() {
1355 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1356 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1358 root = globals->get_fg_root();
1359 if ( ! root.length() ) {
1360 // No root path set? Then bail ...
1361 SG_LOG( SG_GENERAL, SG_ALERT,
1362 "Cannot continue without a path to the base package "
1363 << "being defined." );
1366 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1368 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1370 char buf[512], *cwd = getcwd(buf, 511);
1372 SGPropertyNode *curr = fgGetNode("/sim", true);
1373 curr->removeChild("fg-current", 0, false);
1374 curr = curr->getChild("fg-current", 0, true);
1375 curr->setStringValue(cwd ? cwd : "");
1376 curr->setAttribute(SGPropertyNode::WRITE, false);
1381 // Initialize the flight model subsystem. This just creates the
1382 // object. The actual fdm initialization is delayed until we get a
1383 // proper scenery elevation hit. This is checked for in main.cxx
1387 if ( cur_fdm_state ) {
1388 delete cur_fdm_state;
1392 double dt = 1.0 / fgGetInt("/sim/model-hz");
1393 string model = fgGetString("/sim/flight-model");
1395 if ( model == "larcsim" ) {
1396 cur_fdm_state = new FGLaRCsim( dt );
1397 } else if ( model == "jsb" ) {
1398 cur_fdm_state = new FGJSBsim( dt );
1400 } else if ( model == "ada" ) {
1401 cur_fdm_state = new FGADA( dt );
1402 } else if ( model == "acms" ) {
1403 cur_fdm_state = new FGACMS( dt );
1404 } else if ( model == "balloon" ) {
1405 cur_fdm_state = new FGBalloonSim( dt );
1406 } else if ( model == "magic" ) {
1407 cur_fdm_state = new FGMagicCarpet( dt );
1409 } else if ( model == "ufo" ) {
1410 cur_fdm_state = new FGUFO( dt );
1411 } else if ( model == "external" ) {
1412 // external is a synonym for "--fdm=null" and is
1413 // maintained here for backwards compatibility
1414 cur_fdm_state = new FGNullFDM( dt );
1415 } else if ( model.find("network") == 0 ) {
1416 string host = "localhost";
1420 string net_options = model.substr(8);
1421 string::size_type begin, end;
1424 end = net_options.find( ",", begin );
1425 if ( end != string::npos ) {
1426 host = net_options.substr(begin, end - begin);
1430 end = net_options.find( ",", begin );
1431 if ( end != string::npos ) {
1432 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1436 end = net_options.find( ",", begin );
1437 if ( end != string::npos ) {
1438 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1442 end = net_options.find( ",", begin );
1443 if ( end != string::npos ) {
1444 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1447 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1448 } else if ( model.find("pipe") == 0 ) {
1449 // /* old */ string pipe_path = model.substr(5);
1450 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1451 string pipe_path = "";
1452 string pipe_protocol = "";
1453 string pipe_options = model.substr(5);
1454 string::size_type begin, end;
1457 end = pipe_options.find( ",", begin );
1458 if ( end != string::npos ) {
1459 pipe_path = pipe_options.substr(begin, end - begin);
1462 // protocol (last option)
1463 pipe_protocol = pipe_options.substr(begin);
1464 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1465 } else if ( model == "null" ) {
1466 cur_fdm_state = new FGNullFDM( dt );
1467 } else if ( model == "yasim" ) {
1468 cur_fdm_state = new YASim( dt );
1470 throw sg_throwable(string("Unrecognized flight model '") + model
1471 + "', cannot init flight dynamics model.");
1475 // Initialize view parameters
1477 // force update of model so that viewer can get some data...
1478 globals->get_aircraft_model()->update(0);
1479 // run update for current view so that data is current...
1480 globals->get_viewmgr()->update(0);
1484 SGTime *fgInitTime() {
1486 static const SGPropertyNode *longitude
1487 = fgGetNode("/position/longitude-deg");
1488 static const SGPropertyNode *latitude
1489 = fgGetNode("/position/latitude-deg");
1490 static const SGPropertyNode *cur_time_override
1491 = fgGetNode("/sim/time/cur-time-override", true);
1493 SGPath zone( globals->get_fg_root() );
1494 zone.append( "Timezone" );
1495 SGTime *t = new SGTime( longitude->getDoubleValue()
1496 * SGD_DEGREES_TO_RADIANS,
1497 latitude->getDoubleValue()
1498 * SGD_DEGREES_TO_RADIANS,
1500 cur_time_override->getLongValue() );
1502 globals->set_warp_delta( 0 );
1504 t->update( 0.0, 0.0,
1505 cur_time_override->getLongValue(),
1506 globals->get_warp() );
1512 // set up a time offset (aka warp) if one is specified
1513 void fgInitTimeOffset() {
1514 static const SGPropertyNode *longitude
1515 = fgGetNode("/position/longitude-deg");
1516 static const SGPropertyNode *latitude
1517 = fgGetNode("/position/latitude-deg");
1518 static const SGPropertyNode *cur_time_override
1519 = fgGetNode("/sim/time/cur-time-override", true);
1521 // Handle potential user specified time offsets
1522 int orig_warp = globals->get_warp();
1523 SGTime *t = globals->get_time_params();
1524 time_t cur_time = t->get_cur_time();
1525 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1526 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1527 time_t aircraftLocalTime =
1528 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1530 // Okay, we now have several possible scenarios
1531 int offset = fgGetInt("/sim/startup/time-offset");
1532 string offset_type = fgGetString("/sim/startup/time-offset-type");
1535 if ( offset_type == "real" ) {
1537 } else if ( offset_type == "dawn" ) {
1538 warp = fgTimeSecondsUntilSunAngle( cur_time,
1539 longitude->getDoubleValue()
1540 * SGD_DEGREES_TO_RADIANS,
1541 latitude->getDoubleValue()
1542 * SGD_DEGREES_TO_RADIANS,
1544 } else if ( offset_type == "morning" ) {
1545 warp = fgTimeSecondsUntilSunAngle( cur_time,
1546 longitude->getDoubleValue()
1547 * SGD_DEGREES_TO_RADIANS,
1548 latitude->getDoubleValue()
1549 * SGD_DEGREES_TO_RADIANS,
1551 } else if ( offset_type == "noon" ) {
1552 warp = fgTimeSecondsUntilSunAngle( cur_time,
1553 longitude->getDoubleValue()
1554 * SGD_DEGREES_TO_RADIANS,
1555 latitude->getDoubleValue()
1556 * SGD_DEGREES_TO_RADIANS,
1558 } else if ( offset_type == "afternoon" ) {
1559 warp = fgTimeSecondsUntilSunAngle( cur_time,
1560 longitude->getDoubleValue()
1561 * SGD_DEGREES_TO_RADIANS,
1562 latitude->getDoubleValue()
1563 * SGD_DEGREES_TO_RADIANS,
1565 } else if ( offset_type == "dusk" ) {
1566 warp = fgTimeSecondsUntilSunAngle( cur_time,
1567 longitude->getDoubleValue()
1568 * SGD_DEGREES_TO_RADIANS,
1569 latitude->getDoubleValue()
1570 * SGD_DEGREES_TO_RADIANS,
1572 } else if ( offset_type == "evening" ) {
1573 warp = fgTimeSecondsUntilSunAngle( cur_time,
1574 longitude->getDoubleValue()
1575 * SGD_DEGREES_TO_RADIANS,
1576 latitude->getDoubleValue()
1577 * SGD_DEGREES_TO_RADIANS,
1579 } else if ( offset_type == "midnight" ) {
1580 warp = fgTimeSecondsUntilSunAngle( cur_time,
1581 longitude->getDoubleValue()
1582 * SGD_DEGREES_TO_RADIANS,
1583 latitude->getDoubleValue()
1584 * SGD_DEGREES_TO_RADIANS,
1586 } else if ( offset_type == "system-offset" ) {
1589 } else if ( offset_type == "gmt-offset" ) {
1590 warp = offset - (currGMT - systemLocalTime);
1592 } else if ( offset_type == "latitude-offset" ) {
1593 warp = offset - (aircraftLocalTime - systemLocalTime);
1595 } else if ( offset_type == "system" ) {
1596 warp = offset - (systemLocalTime - currGMT) - cur_time;
1597 } else if ( offset_type == "gmt" ) {
1598 warp = offset - cur_time;
1599 } else if ( offset_type == "latitude" ) {
1600 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1602 SG_LOG( SG_GENERAL, SG_ALERT,
1603 "FG_TIME::Unsupported offset type " << offset_type );
1606 globals->set_warp( orig_warp + warp );
1607 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1608 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1609 cur_time_override->getLongValue(),
1610 globals->get_warp() );
1612 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1613 << globals->get_warp() );
1617 // This is the top level init routine which calls all the other
1618 // initialization routines. If you are adding a subsystem to flight
1619 // gear, its initialization call should located in this routine.
1620 // Returns non-zero if a problem encountered.
1621 bool fgInitSubsystems() {
1622 // static const SGPropertyNode *longitude
1623 // = fgGetNode("/sim/presets/longitude-deg");
1624 // static const SGPropertyNode *latitude
1625 // = fgGetNode("/sim/presets/latitude-deg");
1626 // static const SGPropertyNode *altitude
1627 // = fgGetNode("/sim/presets/altitude-ft");
1628 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1629 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1631 ////////////////////////////////////////////////////////////////////
1632 // Initialize the event manager subsystem.
1633 ////////////////////////////////////////////////////////////////////
1635 globals->get_event_mgr()->init();
1636 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1638 ////////////////////////////////////////////////////////////////////
1639 // Initialize the property interpolator subsystem. Put into the INIT
1640 // group because the "nasal" subsystem may need it at GENERAL take-down.
1641 ////////////////////////////////////////////////////////////////////
1642 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1645 ////////////////////////////////////////////////////////////////////
1646 // Add the FlightGear property utilities.
1647 ////////////////////////////////////////////////////////////////////
1648 globals->add_subsystem("properties", new FGProperties);
1650 ////////////////////////////////////////////////////////////////////
1651 // Initialize the material property subsystem.
1652 ////////////////////////////////////////////////////////////////////
1654 SGPath mpath( globals->get_fg_root() );
1655 mpath.append( "materials.xml" );
1656 string season = fgGetString("/sim/startup/season", "summer");
1657 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1658 globals->get_props()) ) {
1659 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1664 ////////////////////////////////////////////////////////////////////
1665 // Initialize the scenery management subsystem.
1666 ////////////////////////////////////////////////////////////////////
1668 if ( globals->get_tile_mgr()->init() ) {
1669 // Load the local scenery data
1670 double visibility_meters = fgGetDouble("/environment/visibility-m");
1672 globals->get_tile_mgr()->update( visibility_meters );
1674 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1678 globals->get_scenery()->get_scene_graph()
1679 ->addChild(simgear::Particles::getCommonRoot());
1681 ////////////////////////////////////////////////////////////////////
1682 // Initialize the flight model subsystem.
1683 ////////////////////////////////////////////////////////////////////
1687 // allocates structures so must happen before any of the flight
1688 // model or control parameters are set
1689 fgAircraftInit(); // In the future this might not be the case.
1692 ////////////////////////////////////////////////////////////////////
1693 // Initialize the weather subsystem.
1694 ////////////////////////////////////////////////////////////////////
1696 // Initialize the weather modeling subsystem
1697 globals->add_subsystem("environment", new FGEnvironmentMgr);
1700 ////////////////////////////////////////////////////////////////////
1701 // Initialize the aircraft systems and instrumentation (before the
1703 ////////////////////////////////////////////////////////////////////
1705 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1706 globals->add_subsystem("systems", new FGSystemMgr);
1708 ////////////////////////////////////////////////////////////////////
1709 // Initialize the XML Autopilot subsystem.
1710 ////////////////////////////////////////////////////////////////////
1712 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1713 globals->add_subsystem( "route-manager", new FGRouteMgr );
1716 ////////////////////////////////////////////////////////////////////
1717 // Initialize the view manager subsystem.
1718 ////////////////////////////////////////////////////////////////////
1722 ////////////////////////////////////////////////////////////////////
1723 // Create and register the logger.
1724 ////////////////////////////////////////////////////////////////////
1726 globals->add_subsystem("logger", new FGLogger);
1728 ////////////////////////////////////////////////////////////////////
1729 // Create and register the XML GUI.
1730 ////////////////////////////////////////////////////////////////////
1732 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1735 ////////////////////////////////////////////////////////////////////
1736 // Initialize the local time subsystem.
1737 ////////////////////////////////////////////////////////////////////
1739 // update the current timezone each 30 minutes
1740 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1741 &fgUpdateLocalTime, 30*60 );
1742 fgInitTimeOffset(); // the environment subsystem needs this
1745 ////////////////////////////////////////////////////////////////////
1746 // Initialize the lighting subsystem.
1747 ////////////////////////////////////////////////////////////////////
1749 globals->add_subsystem("lighting", new FGLight);
1751 //////////////////////////////////////////////////////////////////////
1752 // Initialize the 2D cloud subsystem.
1753 ////////////////////////////////////////////////////////////////////
1754 fgGetBool("/sim/rendering/bump-mapping", false);
1756 #ifdef ENABLE_AUDIO_SUPPORT
1757 ////////////////////////////////////////////////////////////////////
1758 // Initialize the sound subsystem.
1759 ////////////////////////////////////////////////////////////////////
1761 init_volume = fgGetFloat("/sim/sound/volume");
1762 fgSetFloat("/sim/sound/volume", 0.0f);
1763 globals->set_soundmgr(new SGSoundMgr);
1764 globals->get_soundmgr()->init();
1765 globals->get_soundmgr()->bind();
1768 ////////////////////////////////////////////////////////////////////
1769 // Initialize the sound-effects subsystem.
1770 ////////////////////////////////////////////////////////////////////
1772 globals->add_subsystem("fx", new FGFX);
1773 globals->add_subsystem("voice", new FGVoiceMgr);
1776 ////////////////////////////////////////////////////////////////////
1777 // Initialise the ATC Manager
1778 ////////////////////////////////////////////////////////////////////
1780 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1781 globals->set_ATC_mgr(new FGATCMgr);
1782 globals->get_ATC_mgr()->init();
1784 ////////////////////////////////////////////////////////////////////
1785 // Initialise the AI Manager
1786 ////////////////////////////////////////////////////////////////////
1788 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1789 globals->set_AI_mgr(new FGAIMgr);
1790 globals->get_AI_mgr()->init();
1792 ////////////////////////////////////////////////////////////////////
1793 // Initialise the AI Model Manager
1794 ////////////////////////////////////////////////////////////////////
1795 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1796 globals->add_subsystem("ai_model", new FGAIManager);
1797 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1800 // It's probably a good idea to initialize the top level traffic manager
1801 // After the AI and ATC systems have been initialized properly.
1802 // AI Traffic manager
1803 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1806 ////////////////////////////////////////////////////////////////////
1807 // Initialize the cockpit subsystem
1808 ////////////////////////////////////////////////////////////////////
1809 if( fgCockpitInit( ¤t_aircraft )) {
1810 // Cockpit initialized ok.
1812 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1817 ////////////////////////////////////////////////////////////////////
1818 // Initialize I/O subsystem.
1819 ////////////////////////////////////////////////////////////////////
1821 globals->get_io()->init();
1822 globals->get_io()->bind();
1825 ////////////////////////////////////////////////////////////////////
1826 // Add a new 2D panel.
1827 ////////////////////////////////////////////////////////////////////
1829 string panel_path = fgGetString("/sim/panel/path",
1830 "Panels/Default/default.xml");
1832 globals->set_current_panel( fgReadPanel(panel_path) );
1833 if (globals->get_current_panel() == 0) {
1834 SG_LOG( SG_INPUT, SG_ALERT,
1835 "Error reading new panel from " << panel_path );
1837 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1838 globals->get_current_panel()->init();
1839 globals->get_current_panel()->bind();
1843 ////////////////////////////////////////////////////////////////////
1844 // Initialize the controls subsystem.
1845 ////////////////////////////////////////////////////////////////////
1847 globals->get_controls()->init();
1848 globals->get_controls()->bind();
1851 ////////////////////////////////////////////////////////////////////
1852 // Initialize the input subsystem.
1853 ////////////////////////////////////////////////////////////////////
1855 globals->add_subsystem("input", new FGInput);
1858 ////////////////////////////////////////////////////////////////////
1859 // Initialize the replay subsystem
1860 ////////////////////////////////////////////////////////////////////
1861 globals->add_subsystem("replay", new FGReplay);
1863 ////////////////////////////////////////////////////////////////////
1864 // Bind and initialize subsystems.
1865 ////////////////////////////////////////////////////////////////////
1867 globals->get_subsystem_mgr()->bind();
1868 globals->get_subsystem_mgr()->init();
1870 ////////////////////////////////////////////////////////////////////
1871 // Initialize multiplayer subsystem
1872 ////////////////////////////////////////////////////////////////////
1874 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1875 globals->get_multiplayer_mgr()->init();
1877 ////////////////////////////////////////////////////////////////////////
1878 // Initialize the Nasal interpreter.
1879 // Do this last, so that the loaded scripts see initialized state
1880 ////////////////////////////////////////////////////////////////////////
1881 FGNasalSys* nasal = new FGNasalSys();
1882 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1885 // initialize methods that depend on other subsystems.
1886 globals->get_subsystem_mgr()->postinit();
1888 ////////////////////////////////////////////////////////////////////////
1889 // End of subsystem initialization.
1890 ////////////////////////////////////////////////////////////////////
1892 SG_LOG( SG_GENERAL, SG_INFO, endl);
1894 // Save the initial state for future
1896 globals->saveInitialState();
1902 void fgReInitSubsystems()
1904 // static const SGPropertyNode *longitude
1905 // = fgGetNode("/sim/presets/longitude-deg");
1906 // static const SGPropertyNode *latitude
1907 // = fgGetNode("/sim/presets/latitude-deg");
1908 static const SGPropertyNode *altitude
1909 = fgGetNode("/sim/presets/altitude-ft");
1910 static const SGPropertyNode *master_freeze
1911 = fgGetNode("/sim/freeze/master");
1913 SG_LOG( SG_GENERAL, SG_INFO,
1914 "fgReInitSubsystems(): /position/altitude = "
1915 << altitude->getDoubleValue() );
1917 bool freeze = master_freeze->getBoolValue();
1919 fgSetBool("/sim/freeze/master", true);
1921 fgSetBool("/sim/crashed", false);
1923 // Force reupdating the positions of the ai 3d models. They are used for
1924 // initializing ground level for the FDM.
1925 globals->get_subsystem("ai_model")->reinit();
1927 // Initialize the FDM
1930 // allocates structures so must happen before any of the flight
1931 // model or control parameters are set
1932 fgAircraftInit(); // In the future this might not be the case.
1934 // reload offsets from config defaults
1935 globals->get_viewmgr()->reinit();
1939 globals->get_controls()->reset_all();
1941 fgUpdateLocalTime();
1943 // re-init to proper time of day setting
1947 fgSetBool("/sim/freeze/master", false);
1949 fgSetBool("/sim/sceneryloaded",false);
1953 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1955 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1957 bool freeze = master_freeze->getBoolValue();
1959 master_freeze->setBoolValue(true);
1961 fgSetBool("/sim/signals/reinit", true);
1962 cur_fdm_state->unbind();
1964 // in case user has changed window size as
1965 // restoreInitialState() overwrites these
1966 int xsize = fgGetInt("/sim/startup/xsize");
1967 int ysize = fgGetInt("/sim/startup/ysize");
1969 globals->restoreInitialState();
1971 // update our position based on current presets
1974 // We don't know how to resize the window, so keep the last values
1975 // for xsize and ysize, and don't use the one set initially
1976 fgSetInt("/sim/startup/xsize", xsize);
1977 fgSetInt("/sim/startup/ysize", ysize);
1979 SGTime *t = globals->get_time_params();
1982 globals->set_time_params(t);
1984 fgReInitSubsystems();
1986 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1987 globals->get_renderer()->resize(xsize, ysize);
1988 fgSetBool("/sim/signals/reinit", false);
1991 master_freeze->setBoolValue(false);