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
38 # include <io.h> // isatty()
39 # define isatty _isatty
42 // work around a stdc++ lib bug in some versions of linux, but doesn't
43 // seem to hurt to have this here for all versions of Linux.
45 # define _G_NO_EXTERN_TEMPLATES
48 #include <simgear/compiler.h>
52 #include <simgear/constants.h>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/structure/exception.hxx>
55 #include <simgear/structure/event_mgr.hxx>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/misc/interpolator.hxx>
58 #include <simgear/scene/material/matlib.hxx>
59 #include <simgear/scene/model/particles.hxx>
60 #include <simgear/timing/sg_time.hxx>
61 #include <simgear/timing/lowleveltime.h>
63 #include <Aircraft/aircraft.hxx>
64 #include <Aircraft/controls.hxx>
65 #include <Aircraft/replay.hxx>
66 #include <Airports/apt_loader.hxx>
67 #include <Airports/runways.hxx>
68 #include <Airports/simple.hxx>
69 #include <Airports/dynamics.hxx>
71 #include <AIModel/AIManager.hxx>
72 #include <ATCDCL/ATCmgr.hxx>
73 #include <ATCDCL/AIMgr.hxx>
74 #include <Autopilot/route_mgr.hxx>
75 #include <Autopilot/xmlauto.hxx>
76 #include <Cockpit/cockpit.hxx>
77 #include <Cockpit/panel.hxx>
78 #include <Cockpit/panel_io.hxx>
80 #include <FDM/SP/ADA.hxx>
81 #include <FDM/SP/ACMS.hxx>
82 #include <FDM/SP/MagicCarpet.hxx>
83 #include <FDM/SP/Balloon.h>
85 #include <FDM/ExternalNet/ExternalNet.hxx>
86 #include <FDM/ExternalPipe/ExternalPipe.hxx>
87 #include <FDM/JSBSim/JSBSim.hxx>
88 #include <FDM/LaRCsim/LaRCsim.hxx>
89 #include <FDM/UFO.hxx>
90 #include <FDM/NullFDM.hxx>
91 #include <FDM/YASim/YASim.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <Include/general.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <AIModel/submodel.hxx>
98 #include <AIModel/AIManager.hxx>
99 #include <Navaids/navdb.hxx>
100 #include <Navaids/navlist.hxx>
101 #include <Navaids/fix.hxx>
102 #include <Navaids/fixlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/fg_fx.hxx>
107 #include <Sound/beacon.hxx>
108 #include <Sound/morse.hxx>
109 #include <Sound/voice.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/sunsolver.hxx>
113 #include <Time/tmp.hxx>
114 #include <Traffic/TrafficMgr.hxx>
115 #include <MultiPlayer/multiplaymgr.hxx>
117 #include <Environment/environment_mgr.hxx>
118 #include <Environment/ridge_lift.hxx>
120 #include "fg_init.hxx"
122 #include "fg_commands.hxx"
123 #include "fg_props.hxx"
124 #include "options.hxx"
125 #include "globals.hxx"
126 #include "logger.hxx"
127 #include "renderer.hxx"
128 #include "viewmgr.hxx"
132 # include <CoreFoundation/CoreFoundation.h>
138 extern const char *default_root;
142 // Scan the command line options for the specified option and return
144 static string fgScanForOption( const string& option, int argc, char **argv ) {
147 if (hostname == NULL)
150 gethostname(_hostname, 256);
151 hostname = strdup(_hostname);
152 free_hostname = true;
155 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
157 int len = option.length();
160 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
162 string arg = argv[i];
163 if ( arg.find( option ) == 0 ) {
164 return arg.substr( len );
174 // Scan the user config files for the specified option and return
176 static string fgScanForOption( const string& option, const string& path ) {
177 sg_gzifstream in( path );
178 if ( !in.is_open() ) {
182 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
184 int len = option.length();
187 while ( ! in.eof() ) {
189 getline( in, line, '\n' );
191 // catch extraneous (DOS) line ending character
192 if ( line[line.length() - 1] < 32 ) {
193 line = line.substr( 0, line.length()-1 );
196 if ( line.find( option ) == 0 ) {
197 return line.substr( len );
206 // Scan the user config files for the specified option and return
208 static string fgScanForOption( const string& option ) {
211 #if defined( unix ) || defined( __CYGWIN__ )
212 // Next check home directory for .fgfsrc.hostname file
214 if ( homedir != NULL ) {
215 SGPath config( homedir );
216 config.append( ".fgfsrc" );
217 config.concat( "." );
218 config.concat( hostname );
219 arg = fgScanForOption( option, config.str() );
224 // Next check home directory for .fgfsrc file
226 if ( homedir != NULL ) {
227 SGPath config( homedir );
228 config.append( ".fgfsrc" );
229 arg = fgScanForOption( option, config.str() );
234 // Check for $fg_root/system.fgfsrc
235 SGPath config( globals->get_fg_root() );
236 config.append( "system.fgfsrc" );
237 arg = fgScanForOption( option, config.str() );
244 // Read in configuration (files and command line options) but only set
246 bool fgInitFGRoot ( int argc, char **argv ) {
249 // First parse command line options looking for --fg-root=, this
250 // will override anything specified in a config file
251 root = fgScanForOption( "--fg-root=", argc, argv);
253 // Check in one of the user configuration files.
255 root = fgScanForOption( "--fg-root=" );
257 // Next check if fg-root is set as an env variable
258 if ( root.empty() ) {
259 char *envp = ::getenv( "FG_ROOT" );
260 if ( envp != NULL ) {
265 // Otherwise, default to a random compiled-in location if we can't
266 // find fg-root any other way.
267 if ( root.empty() ) {
268 #if defined( __CYGWIN__ )
269 root = "/FlightGear";
270 #elif defined( WIN32 )
271 root = "\\FlightGear";
272 #elif defined(__APPLE__)
274 The following code looks for the base package inside the application
275 bundle, in the standard Contents/Resources location.
277 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
279 // look for a 'data' subdir
280 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
282 // now convert down to a path, and the a c-string
283 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
284 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
286 CFRelease(resourcesUrl);
294 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
295 globals->set_fg_root(root);
301 // Read in configuration (files and command line options) but only set
303 bool fgInitFGAircraft ( int argc, char **argv ) {
306 // First parse command line options looking for --aircraft=, this
307 // will override anything specified in a config file
308 aircraft = fgScanForOption( "--aircraft=", argc, argv );
309 if ( aircraft.empty() ) {
310 // check synonym option
311 aircraft = fgScanForOption( "--vehicle=", argc, argv );
314 // Check in one of the user configuration files.
315 if ( aircraft.empty() ) {
316 aircraft = fgScanForOption( "--aircraft=" );
318 if ( aircraft.empty() ) {
319 aircraft = fgScanForOption( "--vehicle=" );
322 // if an aircraft was specified, set the property name
323 if ( !aircraft.empty() ) {
324 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
325 fgSetString("/sim/aircraft", aircraft.c_str() );
327 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
334 // Return the current base package version
335 string fgBasePackageVersion() {
336 SGPath base_path( globals->get_fg_root() );
337 base_path.append("version");
339 sg_gzifstream in( base_path.str() );
340 if ( !in.is_open() ) {
341 SGPath old_path( globals->get_fg_root() );
342 old_path.append( "Thanks" );
343 sg_gzifstream old( old_path.str() );
344 if ( !old.is_open() ) {
347 return "[old version]";
358 // Initialize the localization
359 SGPropertyNode *fgInitLocale(const char *language) {
360 SGPropertyNode *c_node = NULL, *d_node = NULL;
361 SGPropertyNode *intl = fgGetNode("/sim/intl");
363 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
365 // localization not defined
370 // Select the proper language from the list
372 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
373 for (unsigned int i = 0; i < locale.size(); i++) {
375 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
376 for (unsigned int j = 0; j < lang.size(); j++) {
378 if (!strcmp(lang[j]->getStringValue(), language)) {
387 d_node = intl->getChild("locale");
391 // Check for localized font
392 SGPropertyNode *font_n = c_node->getNode("font", true);
393 if ( !strcmp(font_n->getStringValue(), "") )
394 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
398 // Load the default strings
400 SGPath d_path( globals->get_fg_root() );
402 const char *d_path_str = d_node->getStringValue("strings");
404 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
408 d_path.append(d_path_str);
409 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
411 SGPropertyNode *strings = c_node->getNode("strings");
413 readProperties(d_path.str(), strings);
414 } catch (const sg_exception &) {
415 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
420 // Load the language specific strings
422 if (c_node != d_node) {
423 SGPath c_path( globals->get_fg_root() );
425 const char *c_path_str = c_node->getStringValue("strings");
427 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
431 c_path.append(c_path_str);
432 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
435 readProperties(c_path.str(), strings);
436 } catch (const sg_exception &) {
437 SG_LOG(SG_GENERAL, SG_ALERT,
438 "Unable to read the localized strings from " << c_path.str());
448 // Initialize the localization routines
449 bool fgDetectLanguage() {
450 const char *language = ::getenv("LANG");
452 if (language == NULL) {
453 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
457 SGPropertyNode *locale = fgInitLocale(language);
459 SG_LOG(SG_GENERAL, SG_ALERT,
460 "No internationalization settings specified in preferences.xml" );
465 globals->set_locale( locale );
470 // Attempt to locate and parse the various non-XML config files in order
471 // from least precidence to greatest precidence
473 do_options (int argc, char ** argv)
475 // Check for $fg_root/system.fgfsrc
476 SGPath config( globals->get_fg_root() );
477 config.append( "system.fgfsrc" );
478 fgParseOptions(config.str());
480 #if defined( unix ) || defined( __CYGWIN__ )
481 config.concat( "." );
482 config.concat( hostname );
483 fgParseOptions(config.str());
486 // Check for ~/.fgfsrc
487 if ( homedir != NULL ) {
488 config.set( homedir );
489 config.append( ".fgfsrc" );
490 fgParseOptions(config.str());
493 #if defined( unix ) || defined( __CYGWIN__ )
494 // Check for ~/.fgfsrc.hostname
495 config.concat( "." );
496 config.concat( hostname );
497 fgParseOptions(config.str());
500 // Parse remaining command line options
501 // These will override anything specified in a config file
502 fgParseArgs(argc, argv);
506 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
507 SGPropertyNode *cache, int depth = 0 )
509 const int MAXDEPTH = 1;
512 ulDir *dirp = ulOpenDir(path.str().c_str());
514 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
519 while ((dire = ulReadDir(dirp)) != NULL) {
521 if (depth > MAXDEPTH)
524 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
525 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
529 next.append(dire->d_name);
531 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
532 if ( ! result.empty() )
536 int len = strlen(dire->d_name);
537 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
543 if (!cache->getChild("aircraft", i++, false))
546 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
548 n = entry->getNode("file", true);
549 n->setStringValue(dire->d_name);
550 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
552 n = entry->getNode("path", true);
553 n->setStringValue(path.str().c_str());
554 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
556 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
568 // Read in configuration (file and command line)
569 bool fgInitConfig ( int argc, char **argv ) {
571 // First, set some sane default values
574 // Read global preferences from $FG_ROOT/preferences.xml
575 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
576 fgLoadProps("preferences.xml", globals->get_props());
577 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
579 // Detect the required language as early as possible
580 if ( !fgDetectLanguage() ) {
584 SGPropertyNode autosave;
585 #if defined( _MSC_VER ) || defined( __MINGW32__ )
586 char *envp = ::getenv( "APPDATA" );
588 SGPath config( envp );
589 config.append( "flightgear.org" );
591 if ( homedir != NULL ) {
592 SGPath config( homedir );
593 config.append( ".fgfs" );
595 const char *fg_home = getenv("FG_HOME");
599 SGPath home_export(config.str());
600 home_export.append("Export/dummy");
601 home_export.create_dir(0777);
603 // Set /sim/fg-home and don't allow malign code to override it until
604 // Nasal security is set up. Use FG_HOME if necessary.
605 SGPropertyNode *home = fgGetNode("/sim", true);
606 home->removeChild("fg-home", 0, false);
607 home = home->getChild("fg-home", 0, true);
608 home->setStringValue(config.c_str());
609 home->setAttribute(SGPropertyNode::WRITE, false);
611 config.append( "autosave.xml" );
612 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
614 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
616 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
618 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
620 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
623 // Scan user config files and command line for a specified aircraft.
624 fgInitFGAircraft(argc, argv);
626 string aircraft = fgGetString( "/sim/aircraft", "" );
627 if ( aircraft.size() > 0 ) {
628 SGPath aircraft_search( globals->get_fg_root() );
629 aircraft_search.append( "Aircraft" );
631 string aircraft_set = aircraft + "-set.xml";
634 // check if the *-set.xml file is already in the cache
635 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
636 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
637 for (unsigned int i = 0; i < cache.size(); i++) {
638 const char *name = cache[i]->getStringValue("file", "");
639 if (aircraft_set == name) {
640 const char *path = cache[i]->getStringValue("path", "");
650 if (result.empty()) {
651 // prepare cache for rescan
652 SGPropertyNode *n = cache_root->getNode("fg-root", true);
653 n->setStringValue(globals->get_fg_root().c_str());
654 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
655 cache_root->removeChildren("aircraft");
657 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
660 if ( !result.empty() ) {
661 fgSetString( "/sim/aircraft-dir", result.c_str() );
662 SGPath full_name( result );
663 full_name.append( aircraft_set );
665 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
666 << " from " << full_name.str());
668 readProperties( full_name.str(), globals->get_props() );
669 } catch ( const sg_exception &e ) {
670 string message = "Error reading default aircraft: ";
671 message += e.getFormattedMessage();
672 SG_LOG(SG_INPUT, SG_ALERT, message);
676 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
682 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
685 copyProperties(&autosave, globals->get_props());
687 // parse options after loading aircraft to ensure any user
688 // overrides of defaults are honored.
689 do_options(argc, argv);
694 // Set current tower position lon/lat given an airport id
695 static bool fgSetTowerPosFromAirportID( const string& id) {
696 const FGAirport *a = fgFindAirportID( id);
698 SGGeod tower = a->getTowerLocation();
699 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
700 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
701 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
709 struct FGTowerLocationListener : SGPropertyChangeListener {
710 void valueChanged(SGPropertyNode* node) {
711 const string id(node->getStringValue());
712 fgSetTowerPosFromAirportID(id);
716 void fgInitTowerLocationListener() {
717 fgGetNode("/sim/tower/airport-id", true)
718 ->addChangeListener( new FGTowerLocationListener(), true );
721 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
723 SGGeod startPos(aStartPos);
724 if (aTargetHeading == HUGE_VAL) {
725 aTargetHeading = aHeading;
728 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
729 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
730 offsetDistance *= SG_NM_TO_METER;
731 double offsetAzimuth = aHeading;
732 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
733 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
734 aHeading = aTargetHeading;
739 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
744 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
745 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
746 fgSetDouble("/sim/presets/heading-deg", aHeading );
748 // other code depends on the actual values being set ...
749 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
750 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
751 fgSetDouble("/orientation/heading-deg", aHeading );
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->ident().c_str());
769 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
770 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
774 // Set current_options lon/lat given an airport id and parkig position name
775 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
779 // can't see an easy way around this const_cast at the moment
780 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
782 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
785 FGAirportDynamics* dcs = apt->getDynamics();
787 SG_LOG( SG_GENERAL, SG_ALERT,
788 "Failed to find parking position " << parkpos <<
789 " at airport " << id );
793 int park_index = dcs->getNrOfParkings() - 1;
794 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
795 if (park_index < 0) {
796 SG_LOG( SG_GENERAL, SG_ALERT,
797 "Failed to find parking position " << parkpos <<
798 " at airport " << id );
801 FGParking* parking = dcs->getParking(park_index);
803 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
804 parking->getHeading());
809 // Set current_options lon/lat given an airport id and runway number
810 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
814 // set initial position from airport and runway number
815 SG_LOG( SG_GENERAL, SG_INFO,
816 "Attempting to set starting position for "
817 << id << ":" << rwy );
819 const FGAirport* apt = fgFindAirportID(id);
821 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
825 if (!apt->hasRunwayWithIdent(rwy)) {
826 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
827 "Failed to find runway " << rwy <<
828 " at airport " << id << ". Using default runway." );
832 FGRunway* r(apt->getRunwayByIdent(rwy));
833 fgSetString("/sim/atc/runway", r->ident().c_str());
834 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
835 fgApplyStartOffset(startPos, r->headingDeg());
840 static void fgSetDistOrAltFromGlideSlope() {
841 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
842 string apt_id = fgGetString("/sim/presets/airport-id");
843 double gs = fgGetDouble("/sim/presets/glideslope-deg")
844 * SG_DEGREES_TO_RADIANS ;
845 double od = fgGetDouble("/sim/presets/offset-distance-nm");
846 double alt = fgGetDouble("/sim/presets/altitude-ft");
848 double apt_elev = 0.0;
849 if ( ! apt_id.empty() ) {
850 apt_elev = fgGetAirportElev( apt_id );
851 if ( apt_elev < -9990.0 ) {
858 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
859 // set altitude from glideslope and offset-distance
860 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
861 alt = fabs(od*tan(gs)) + apt_elev;
862 fgSetDouble("/sim/presets/altitude-ft", alt);
863 fgSetBool("/sim/presets/onground", false);
864 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
866 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
867 // set offset-distance from glideslope and altitude
868 od = (alt - apt_elev) / tan(gs);
869 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
870 fgSetDouble("/sim/presets/offset-distance-nm", od);
871 fgSetBool("/sim/presets/onground", false);
872 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
874 } else if( fabs(gs) > 0.01 ) {
875 SG_LOG( SG_GENERAL, SG_ALERT,
876 "Glideslope given but not altitude or offset-distance." );
877 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
878 fgSetDouble("/sim/presets/glideslope-deg", 0);
879 fgSetBool("/sim/presets/onground", true);
884 // Set current_options lon/lat given an airport id and heading (degrees)
885 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
887 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
890 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
891 << id << ":" << freq );
895 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
899 // Set current_options lon/lat given an aircraft carrier id
900 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
902 // set initial position from runway and heading
906 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
907 double lon = geodPos.getLongitudeDeg();
908 double lat = geodPos.getLatitudeDeg();
909 double alt = geodPos.getElevationFt();
911 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
912 << carrier << " at lat = " << lat << ", lon = " << lon
913 << ", alt = " << alt << ", heading = " << heading);
915 fgSetDouble("/sim/presets/longitude-deg", lon);
916 fgSetDouble("/sim/presets/latitude-deg", lat);
917 fgSetDouble("/sim/presets/altitude-ft", alt);
918 fgSetDouble("/sim/presets/heading-deg", heading);
919 fgSetDouble("/position/longitude-deg", lon);
920 fgSetDouble("/position/latitude-deg", lat);
921 fgSetDouble("/position/altitude-ft", alt);
922 fgSetDouble("/orientation/heading-deg", heading);
924 fgSetString("/sim/presets/speed-set", "UVW");
925 fgSetDouble("/velocities/uBody-fps", uvw(0));
926 fgSetDouble("/velocities/vBody-fps", uvw(1));
927 fgSetDouble("/velocities/wBody-fps", uvw(2));
928 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
929 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
930 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
932 fgSetBool("/sim/presets/onground", true);
936 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
942 // Set current_options lon/lat given an airport id and heading (degrees)
943 static bool fgSetPosFromFix( const string& id )
945 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
946 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
948 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
952 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
957 * Initialize vor/ndb/ils/fix list management and query systems (as
958 * well as simple airport db list)
963 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
965 SGPath aptdb( globals->get_fg_root() );
966 aptdb.append( "Airports/apt.dat" );
968 SGPath p_metar( globals->get_fg_root() );
969 p_metar.append( "Airports/metar.dat" );
971 fgAirportDBLoad( aptdb.str(), p_metar.str() );
973 FGNavList *navlist = new FGNavList;
974 FGNavList *loclist = new FGNavList;
975 FGNavList *gslist = new FGNavList;
976 FGNavList *dmelist = new FGNavList;
977 FGNavList *tacanlist = new FGNavList;
978 FGNavList *carrierlist = new FGNavList;
979 FGTACANList *channellist = new FGTACANList;
981 globals->set_navlist( navlist );
982 globals->set_loclist( loclist );
983 globals->set_gslist( gslist );
984 globals->set_dmelist( dmelist );
985 globals->set_tacanlist( tacanlist );
986 globals->set_carrierlist( carrierlist );
987 globals->set_channellist( channellist );
989 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
990 SG_LOG( SG_GENERAL, SG_ALERT,
991 "Problems loading one or more navigational database" );
994 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
995 SGPath p_fix( globals->get_fg_root() );
996 p_fix.append( "Navaids/fix.dat" );
998 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1000 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1001 SGPath p_awy( globals->get_fg_root() );
1002 p_awy.append( "Navaids/awy.dat" );
1003 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1004 //cerr << "Loading Airways" << endl;
1005 awyNet->load (p_awy );
1007 //cerr << "initializing airways" << endl;
1008 globals->set_airwaynet( awyNet );
1014 // Set the initial position based on presets (or defaults)
1015 bool fgInitPosition() {
1016 // cout << "fgInitPosition()" << endl;
1017 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1018 * SG_DEGREES_TO_RADIANS ;
1019 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1020 double alt = fgGetDouble("/sim/presets/altitude-ft");
1022 bool set_pos = false;
1024 // If glideslope is specified, then calculate offset-distance or
1025 // altitude relative to glide slope if either of those was not
1027 if ( fabs( gs ) > 0.01 ) {
1028 fgSetDistOrAltFromGlideSlope();
1032 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1033 // If not, check for an airport-id and use that.
1034 // If not, default to the middle of the KSFO field.
1035 // The default values for lon/lat are deliberately out of range
1036 // so that the airport-id can take effect; valid lon/lat will
1037 // override airport-id, however.
1038 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1039 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1040 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1041 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1046 string apt = fgGetString("/sim/presets/airport-id");
1047 string rwy_no = fgGetString("/sim/presets/runway");
1048 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1049 string vor = fgGetString("/sim/presets/vor-id");
1050 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1051 string ndb = fgGetString("/sim/presets/ndb-id");
1052 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1053 string carrier = fgGetString("/sim/presets/carrier");
1054 string parkpos = fgGetString("/sim/presets/parkpos");
1055 string fix = fgGetString("/sim/presets/fix");
1056 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1057 double hdg = hdg_preset->getDoubleValue();
1059 // save some start parameters, so that we can later say what the
1060 // user really requested. TODO generalize that and move it to options.cxx
1061 static bool start_options_saved = false;
1062 if (!start_options_saved) {
1063 start_options_saved = true;
1064 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1066 opt->setDoubleValue("latitude-deg", lat_deg);
1067 opt->setDoubleValue("longitude-deg", lon_deg);
1068 opt->setDoubleValue("heading-deg", hdg);
1069 opt->setStringValue("airport", apt.c_str());
1070 opt->setStringValue("runway", rwy_no.c_str());
1074 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1076 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1077 // An airport + parking position is requested
1078 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1079 // set tower position
1080 fgSetString("/sim/tower/airport-id", apt.c_str());
1085 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1086 // An airport + runway is requested
1087 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1088 // set tower position (a little off the heading for single
1090 fgSetString("/sim/tower/airport-id", apt.c_str());
1095 if ( !set_pos && !apt.empty() ) {
1096 // An airport is requested (find runway closest to hdg)
1097 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1098 // set tower position (a little off the heading for single
1100 fgSetString("/sim/tower/airport-id", apt.c_str());
1105 if (hdg_preset->getDoubleValue() > 9990.0)
1106 hdg_preset->setDoubleValue(hdg);
1108 if ( !set_pos && !vor.empty() ) {
1109 // a VOR is requested
1110 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1115 if ( !set_pos && !ndb.empty() ) {
1116 // an NDB is requested
1117 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1122 if ( !set_pos && !carrier.empty() ) {
1123 // an aircraft carrier is requested
1124 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1129 if ( !set_pos && !fix.empty() ) {
1130 // a Fix is requested
1131 if ( fgSetPosFromFix( fix ) ) {
1137 // No lon/lat specified, no airport specified, default to
1138 // middle of KSFO field.
1139 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1140 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1143 fgSetDouble( "/position/longitude-deg",
1144 fgGetDouble("/sim/presets/longitude-deg") );
1145 fgSetDouble( "/position/latitude-deg",
1146 fgGetDouble("/sim/presets/latitude-deg") );
1147 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1149 // determine if this should be an on-ground or in-air start
1150 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1151 fgSetBool("/sim/presets/onground", false);
1153 fgSetBool("/sim/presets/onground", true);
1160 // General house keeping initializations
1161 bool fgInitGeneral() {
1164 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1165 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1167 root = globals->get_fg_root();
1168 if ( ! root.length() ) {
1169 // No root path set? Then bail ...
1170 SG_LOG( SG_GENERAL, SG_ALERT,
1171 "Cannot continue without a path to the base package "
1172 << "being defined." );
1175 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1177 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1179 char buf[512], *cwd = getcwd(buf, 511);
1181 SGPropertyNode *curr = fgGetNode("/sim", true);
1182 curr->removeChild("fg-current", 0, false);
1183 curr = curr->getChild("fg-current", 0, true);
1184 curr->setStringValue(cwd ? cwd : "");
1185 curr->setAttribute(SGPropertyNode::WRITE, false);
1187 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1188 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1193 // Initialize the flight model subsystem. This just creates the
1194 // object. The actual fdm initialization is delayed until we get a
1195 // proper scenery elevation hit. This is checked for in main.cxx
1199 if ( cur_fdm_state ) {
1200 delete cur_fdm_state;
1204 double dt = 1.0 / fgGetInt("/sim/model-hz");
1205 string model = fgGetString("/sim/flight-model");
1207 if ( model == "larcsim" ) {
1208 cur_fdm_state = new FGLaRCsim( dt );
1209 } else if ( model == "jsb" ) {
1210 cur_fdm_state = new FGJSBsim( dt );
1212 } else if ( model == "ada" ) {
1213 cur_fdm_state = new FGADA( dt );
1214 } else if ( model == "acms" ) {
1215 cur_fdm_state = new FGACMS( dt );
1216 } else if ( model == "balloon" ) {
1217 cur_fdm_state = new FGBalloonSim( dt );
1218 } else if ( model == "magic" ) {
1219 cur_fdm_state = new FGMagicCarpet( dt );
1221 } else if ( model == "ufo" ) {
1222 cur_fdm_state = new FGUFO( dt );
1223 } else if ( model == "external" ) {
1224 // external is a synonym for "--fdm=null" and is
1225 // maintained here for backwards compatibility
1226 cur_fdm_state = new FGNullFDM( dt );
1227 } else if ( model.find("network") == 0 ) {
1228 string host = "localhost";
1232 string net_options = model.substr(8);
1233 string::size_type begin, end;
1236 end = net_options.find( ",", begin );
1237 if ( end != string::npos ) {
1238 host = net_options.substr(begin, end - begin);
1242 end = net_options.find( ",", begin );
1243 if ( end != string::npos ) {
1244 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1248 end = net_options.find( ",", begin );
1249 if ( end != string::npos ) {
1250 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1254 end = net_options.find( ",", begin );
1255 if ( end != string::npos ) {
1256 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1259 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1260 } else if ( model.find("pipe") == 0 ) {
1261 // /* old */ string pipe_path = model.substr(5);
1262 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1263 string pipe_path = "";
1264 string pipe_protocol = "";
1265 string pipe_options = model.substr(5);
1266 string::size_type begin, end;
1269 end = pipe_options.find( ",", begin );
1270 if ( end != string::npos ) {
1271 pipe_path = pipe_options.substr(begin, end - begin);
1274 // protocol (last option)
1275 pipe_protocol = pipe_options.substr(begin);
1276 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1277 } else if ( model == "null" ) {
1278 cur_fdm_state = new FGNullFDM( dt );
1279 } else if ( model == "yasim" ) {
1280 cur_fdm_state = new YASim( dt );
1282 throw sg_exception(string("Unrecognized flight model '") + model
1283 + "', cannot init flight dynamics model.");
1287 // Initialize view parameters
1289 // force update of model so that viewer can get some data...
1290 globals->get_aircraft_model()->update(0);
1291 // run update for current view so that data is current...
1292 globals->get_viewmgr()->update(0);
1296 SGTime *fgInitTime() {
1298 static const SGPropertyNode *longitude
1299 = fgGetNode("/position/longitude-deg");
1300 static const SGPropertyNode *latitude
1301 = fgGetNode("/position/latitude-deg");
1302 static const SGPropertyNode *cur_time_override
1303 = fgGetNode("/sim/time/cur-time-override", true);
1305 SGPath zone( globals->get_fg_root() );
1306 zone.append( "Timezone" );
1307 SGTime *t = new SGTime( longitude->getDoubleValue()
1308 * SGD_DEGREES_TO_RADIANS,
1309 latitude->getDoubleValue()
1310 * SGD_DEGREES_TO_RADIANS,
1312 cur_time_override->getLongValue() );
1314 globals->set_warp_delta( 0 );
1316 t->update( 0.0, 0.0,
1317 cur_time_override->getLongValue(),
1318 globals->get_warp() );
1324 // set up a time offset (aka warp) if one is specified
1325 void fgInitTimeOffset() {
1326 static const SGPropertyNode *longitude
1327 = fgGetNode("/position/longitude-deg");
1328 static const SGPropertyNode *latitude
1329 = fgGetNode("/position/latitude-deg");
1330 static const SGPropertyNode *cur_time_override
1331 = fgGetNode("/sim/time/cur-time-override", true);
1333 // Handle potential user specified time offsets
1334 int orig_warp = globals->get_warp();
1335 SGTime *t = globals->get_time_params();
1336 time_t cur_time = t->get_cur_time();
1337 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1338 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1339 time_t aircraftLocalTime =
1340 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1342 // Okay, we now have several possible scenarios
1343 int offset = fgGetInt("/sim/startup/time-offset");
1344 string offset_type = fgGetString("/sim/startup/time-offset-type");
1347 if ( offset_type == "real" ) {
1349 } else if ( offset_type == "dawn" ) {
1350 warp = fgTimeSecondsUntilSunAngle( cur_time,
1351 longitude->getDoubleValue()
1352 * SGD_DEGREES_TO_RADIANS,
1353 latitude->getDoubleValue()
1354 * SGD_DEGREES_TO_RADIANS,
1356 } else if ( offset_type == "morning" ) {
1357 warp = fgTimeSecondsUntilSunAngle( cur_time,
1358 longitude->getDoubleValue()
1359 * SGD_DEGREES_TO_RADIANS,
1360 latitude->getDoubleValue()
1361 * SGD_DEGREES_TO_RADIANS,
1363 } else if ( offset_type == "noon" ) {
1364 warp = fgTimeSecondsUntilSunAngle( cur_time,
1365 longitude->getDoubleValue()
1366 * SGD_DEGREES_TO_RADIANS,
1367 latitude->getDoubleValue()
1368 * SGD_DEGREES_TO_RADIANS,
1370 } else if ( offset_type == "afternoon" ) {
1371 warp = fgTimeSecondsUntilSunAngle( cur_time,
1372 longitude->getDoubleValue()
1373 * SGD_DEGREES_TO_RADIANS,
1374 latitude->getDoubleValue()
1375 * SGD_DEGREES_TO_RADIANS,
1377 } else if ( offset_type == "dusk" ) {
1378 warp = fgTimeSecondsUntilSunAngle( cur_time,
1379 longitude->getDoubleValue()
1380 * SGD_DEGREES_TO_RADIANS,
1381 latitude->getDoubleValue()
1382 * SGD_DEGREES_TO_RADIANS,
1384 } else if ( offset_type == "evening" ) {
1385 warp = fgTimeSecondsUntilSunAngle( cur_time,
1386 longitude->getDoubleValue()
1387 * SGD_DEGREES_TO_RADIANS,
1388 latitude->getDoubleValue()
1389 * SGD_DEGREES_TO_RADIANS,
1391 } else if ( offset_type == "midnight" ) {
1392 warp = fgTimeSecondsUntilSunAngle( cur_time,
1393 longitude->getDoubleValue()
1394 * SGD_DEGREES_TO_RADIANS,
1395 latitude->getDoubleValue()
1396 * SGD_DEGREES_TO_RADIANS,
1398 } else if ( offset_type == "system-offset" ) {
1401 } else if ( offset_type == "gmt-offset" ) {
1402 warp = offset - (currGMT - systemLocalTime);
1404 } else if ( offset_type == "latitude-offset" ) {
1405 warp = offset - (aircraftLocalTime - systemLocalTime);
1407 } else if ( offset_type == "system" ) {
1408 warp = offset - (systemLocalTime - currGMT) - cur_time;
1409 } else if ( offset_type == "gmt" ) {
1410 warp = offset - cur_time;
1411 } else if ( offset_type == "latitude" ) {
1412 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1414 SG_LOG( SG_GENERAL, SG_ALERT,
1415 "FG_TIME::Unsupported offset type " << offset_type );
1418 globals->set_warp( orig_warp + warp );
1419 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1420 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1421 cur_time_override->getLongValue(),
1422 globals->get_warp() );
1424 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1425 << globals->get_warp() );
1429 // This is the top level init routine which calls all the other
1430 // initialization routines. If you are adding a subsystem to flight
1431 // gear, its initialization call should located in this routine.
1432 // Returns non-zero if a problem encountered.
1433 bool fgInitSubsystems() {
1434 // static const SGPropertyNode *longitude
1435 // = fgGetNode("/sim/presets/longitude-deg");
1436 // static const SGPropertyNode *latitude
1437 // = fgGetNode("/sim/presets/latitude-deg");
1438 // static const SGPropertyNode *altitude
1439 // = fgGetNode("/sim/presets/altitude-ft");
1440 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1441 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1443 ////////////////////////////////////////////////////////////////////
1444 // Initialize the event manager subsystem.
1445 ////////////////////////////////////////////////////////////////////
1447 globals->get_event_mgr()->init();
1448 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1450 ////////////////////////////////////////////////////////////////////
1451 // Initialize the property interpolator subsystem. Put into the INIT
1452 // group because the "nasal" subsystem may need it at GENERAL take-down.
1453 ////////////////////////////////////////////////////////////////////
1454 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1457 ////////////////////////////////////////////////////////////////////
1458 // Add the FlightGear property utilities.
1459 ////////////////////////////////////////////////////////////////////
1460 globals->add_subsystem("properties", new FGProperties);
1462 ////////////////////////////////////////////////////////////////////
1463 // Initialize the material property subsystem.
1464 ////////////////////////////////////////////////////////////////////
1466 SGPath mpath( globals->get_fg_root() );
1467 mpath.append( "materials.xml" );
1468 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1469 globals->get_props()) ) {
1470 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1475 ////////////////////////////////////////////////////////////////////
1476 // Initialize the scenery management subsystem.
1477 ////////////////////////////////////////////////////////////////////
1479 if ( globals->get_tile_mgr()->init() ) {
1480 // Load the local scenery data
1481 double visibility_meters = fgGetDouble("/environment/visibility-m");
1483 globals->get_tile_mgr()->update( visibility_meters );
1485 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1489 globals->get_scenery()->get_scene_graph()
1490 ->addChild(simgear::Particles::getCommonRoot());
1491 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1493 ////////////////////////////////////////////////////////////////////
1494 // Initialize the flight model subsystem.
1495 ////////////////////////////////////////////////////////////////////
1499 // allocates structures so must happen before any of the flight
1500 // model or control parameters are set
1501 fgAircraftInit(); // In the future this might not be the case.
1504 ////////////////////////////////////////////////////////////////////
1505 // Initialize the weather subsystem.
1506 ////////////////////////////////////////////////////////////////////
1508 // Initialize the weather modeling subsystem
1509 globals->add_subsystem("environment", new FGEnvironmentMgr);
1511 ////////////////////////////////////////////////////////////////////
1512 // Initialize the ridge lift simulation.
1513 ////////////////////////////////////////////////////////////////////
1515 // Initialize the ridgelift subsystem
1516 globals->add_subsystem("ridgelift", new FGRidgeLift);
1519 ////////////////////////////////////////////////////////////////////
1520 // Initialize the aircraft systems and instrumentation (before the
1522 ////////////////////////////////////////////////////////////////////
1524 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1525 globals->add_subsystem("systems", new FGSystemMgr);
1527 ////////////////////////////////////////////////////////////////////
1528 // Initialize the XML Autopilot subsystem.
1529 ////////////////////////////////////////////////////////////////////
1531 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1532 globals->add_subsystem( "route-manager", new FGRouteMgr );
1535 ////////////////////////////////////////////////////////////////////
1536 // Initialize the view manager subsystem.
1537 ////////////////////////////////////////////////////////////////////
1541 ////////////////////////////////////////////////////////////////////
1542 // Create and register the logger.
1543 ////////////////////////////////////////////////////////////////////
1545 globals->add_subsystem("logger", new FGLogger);
1547 ////////////////////////////////////////////////////////////////////
1548 // Create and register the XML GUI.
1549 ////////////////////////////////////////////////////////////////////
1551 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1554 ////////////////////////////////////////////////////////////////////
1555 // Initialize the local time subsystem.
1556 ////////////////////////////////////////////////////////////////////
1558 // update the current timezone each 30 minutes
1559 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1560 &fgUpdateLocalTime, 30*60 );
1561 fgInitTimeOffset(); // the environment subsystem needs this
1564 ////////////////////////////////////////////////////////////////////
1565 // Initialize the lighting subsystem.
1566 ////////////////////////////////////////////////////////////////////
1568 globals->add_subsystem("lighting", new FGLight);
1570 //////////////////////////////////////////////////////////////////////
1571 // Initialize the 2D cloud subsystem.
1572 ////////////////////////////////////////////////////////////////////
1573 fgGetBool("/sim/rendering/bump-mapping", false);
1575 #ifdef ENABLE_AUDIO_SUPPORT
1576 ////////////////////////////////////////////////////////////////////
1577 // Initialize the sound subsystem.
1578 ////////////////////////////////////////////////////////////////////
1580 init_volume = fgGetFloat("/sim/sound/volume");
1581 fgSetFloat("/sim/sound/volume", 0.0f);
1582 globals->set_soundmgr(new SGSoundMgr);
1583 globals->get_soundmgr()->init();
1584 globals->get_soundmgr()->bind();
1587 ////////////////////////////////////////////////////////////////////
1588 // Initialize the sound-effects subsystem.
1589 ////////////////////////////////////////////////////////////////////
1591 globals->add_subsystem("fx", new FGFX);
1592 globals->add_subsystem("voice", new FGVoiceMgr);
1595 ////////////////////////////////////////////////////////////////////
1596 // Initialise the ATC Manager
1597 ////////////////////////////////////////////////////////////////////
1599 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1600 globals->set_ATC_mgr(new FGATCMgr);
1601 globals->get_ATC_mgr()->init();
1603 ////////////////////////////////////////////////////////////////////
1604 // Initialise the AI Manager
1605 ////////////////////////////////////////////////////////////////////
1607 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1608 globals->set_AI_mgr(new FGAIMgr);
1609 globals->get_AI_mgr()->init();
1611 ////////////////////////////////////////////////////////////////////
1612 // Initialise the AI Model Manager
1613 ////////////////////////////////////////////////////////////////////
1614 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1615 globals->add_subsystem("ai_model", new FGAIManager);
1616 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1619 // It's probably a good idea to initialize the top level traffic manager
1620 // After the AI and ATC systems have been initialized properly.
1621 // AI Traffic manager
1622 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1625 ////////////////////////////////////////////////////////////////////
1626 // Initialize the cockpit subsystem
1627 ////////////////////////////////////////////////////////////////////
1628 if( fgCockpitInit( ¤t_aircraft )) {
1629 // Cockpit initialized ok.
1631 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1636 ////////////////////////////////////////////////////////////////////
1637 // Initialize I/O subsystem.
1638 ////////////////////////////////////////////////////////////////////
1640 globals->get_io()->init();
1641 globals->get_io()->bind();
1644 ////////////////////////////////////////////////////////////////////
1645 // Add a new 2D panel.
1646 ////////////////////////////////////////////////////////////////////
1648 string panel_path = fgGetString("/sim/panel/path",
1649 "Panels/Default/default.xml");
1651 globals->set_current_panel( fgReadPanel(panel_path) );
1652 if (globals->get_current_panel() == 0) {
1653 SG_LOG( SG_INPUT, SG_ALERT,
1654 "Error reading new panel from " << panel_path );
1656 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1657 globals->get_current_panel()->init();
1658 globals->get_current_panel()->bind();
1662 ////////////////////////////////////////////////////////////////////
1663 // Initialize the controls subsystem.
1664 ////////////////////////////////////////////////////////////////////
1666 globals->get_controls()->init();
1667 globals->get_controls()->bind();
1670 ////////////////////////////////////////////////////////////////////
1671 // Initialize the input subsystem.
1672 ////////////////////////////////////////////////////////////////////
1674 globals->add_subsystem("input", new FGInput);
1677 ////////////////////////////////////////////////////////////////////
1678 // Initialize the replay subsystem
1679 ////////////////////////////////////////////////////////////////////
1680 globals->add_subsystem("replay", new FGReplay);
1682 ////////////////////////////////////////////////////////////////////
1683 // Bind and initialize subsystems.
1684 ////////////////////////////////////////////////////////////////////
1686 globals->get_subsystem_mgr()->bind();
1687 globals->get_subsystem_mgr()->init();
1689 ////////////////////////////////////////////////////////////////////
1690 // Initialize multiplayer subsystem
1691 ////////////////////////////////////////////////////////////////////
1693 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1694 globals->get_multiplayer_mgr()->init();
1696 ////////////////////////////////////////////////////////////////////////
1697 // Initialize the Nasal interpreter.
1698 // Do this last, so that the loaded scripts see initialized state
1699 ////////////////////////////////////////////////////////////////////////
1700 FGNasalSys* nasal = new FGNasalSys();
1701 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1704 // initialize methods that depend on other subsystems.
1705 globals->get_subsystem_mgr()->postinit();
1707 ////////////////////////////////////////////////////////////////////////
1708 // End of subsystem initialization.
1709 ////////////////////////////////////////////////////////////////////
1711 SG_LOG( SG_GENERAL, SG_INFO, endl);
1713 // Save the initial state for future
1715 globals->saveInitialState();
1721 void fgReInitSubsystems()
1723 // static const SGPropertyNode *longitude
1724 // = fgGetNode("/sim/presets/longitude-deg");
1725 // static const SGPropertyNode *latitude
1726 // = fgGetNode("/sim/presets/latitude-deg");
1727 static const SGPropertyNode *altitude
1728 = fgGetNode("/sim/presets/altitude-ft");
1729 static const SGPropertyNode *master_freeze
1730 = fgGetNode("/sim/freeze/master");
1732 SG_LOG( SG_GENERAL, SG_INFO,
1733 "fgReInitSubsystems(): /position/altitude = "
1734 << altitude->getDoubleValue() );
1736 bool freeze = master_freeze->getBoolValue();
1738 fgSetBool("/sim/freeze/master", true);
1740 fgSetBool("/sim/crashed", false);
1742 // Force reupdating the positions of the ai 3d models. They are used for
1743 // initializing ground level for the FDM.
1744 globals->get_subsystem("ai_model")->reinit();
1746 // Initialize the FDM
1749 // allocates structures so must happen before any of the flight
1750 // model or control parameters are set
1751 fgAircraftInit(); // In the future this might not be the case.
1753 // reload offsets from config defaults
1754 globals->get_viewmgr()->reinit();
1758 globals->get_controls()->reset_all();
1760 fgUpdateLocalTime();
1762 // re-init to proper time of day setting
1766 fgSetBool("/sim/freeze/master", false);
1768 fgSetBool("/sim/sceneryloaded",false);
1772 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1774 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1776 bool freeze = master_freeze->getBoolValue();
1778 master_freeze->setBoolValue(true);
1780 fgSetBool("/sim/signals/reinit", true);
1781 cur_fdm_state->unbind();
1783 // in case user has changed window size as
1784 // restoreInitialState() overwrites these
1785 int xsize = fgGetInt("/sim/startup/xsize");
1786 int ysize = fgGetInt("/sim/startup/ysize");
1788 // viewports also needs to be saved/restored as
1789 // restoreInitialState() overwrites these
1790 SGPropertyNode *guiNode = new SGPropertyNode;
1791 SGPropertyNode *cameraNode = new SGPropertyNode;
1792 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1793 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1794 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1796 globals->restoreInitialState();
1798 // update our position based on current presets
1801 // We don't know how to resize the window, so keep the last values
1802 // for xsize and ysize, and don't use the one set initially
1803 fgSetInt("/sim/startup/xsize", xsize);
1804 fgSetInt("/sim/startup/ysize", ysize);
1806 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1807 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1812 SGTime *t = globals->get_time_params();
1815 globals->set_time_params(t);
1817 fgReInitSubsystems();
1819 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1820 globals->get_renderer()->resize(xsize, ysize);
1821 fgSetBool("/sim/signals/reinit", false);
1824 master_freeze->setBoolValue(false);