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
40 # include "Winsock2.h" // for gethostname()
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
46 # define _G_NO_EXTERN_TEMPLATES
49 #include <simgear/compiler.h>
52 #include <boost/algorithm/string/compare.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/interpolator.hxx>
61 #include <simgear/scene/material/matlib.hxx>
62 #include <simgear/scene/model/particles.hxx>
63 #include <simgear/timing/sg_time.hxx>
64 #include <simgear/timing/lowleveltime.h>
66 #include <Aircraft/aircraft.hxx>
67 #include <Aircraft/controls.hxx>
68 #include <Aircraft/replay.hxx>
69 #include <Airports/apt_loader.hxx>
70 #include <Airports/runways.hxx>
71 #include <Airports/simple.hxx>
72 #include <Airports/dynamics.hxx>
74 #include <AIModel/AIManager.hxx>
75 #include <ATCDCL/ATCmgr.hxx>
76 #include <ATCDCL/AIMgr.hxx>
77 #include <Autopilot/route_mgr.hxx>
78 #include <Autopilot/xmlauto.hxx>
79 #include <Autopilot/autobrake.hxx>
81 #include <Cockpit/cockpit.hxx>
82 #include <Cockpit/panel.hxx>
83 #include <Cockpit/panel_io.hxx>
85 #include <FDM/SP/ADA.hxx>
86 #include <FDM/SP/ACMS.hxx>
87 #include <FDM/SP/MagicCarpet.hxx>
88 #include <FDM/SP/Balloon.h>
90 #include <FDM/ExternalNet/ExternalNet.hxx>
91 #include <FDM/ExternalPipe/ExternalPipe.hxx>
92 #include <FDM/JSBSim/JSBSim.hxx>
93 #include <FDM/LaRCsim/LaRCsim.hxx>
94 #include <FDM/UFO.hxx>
95 #include <FDM/NullFDM.hxx>
96 #include <FDM/YASim/YASim.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <Include/general.hxx>
99 #include <Input/input.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 #include <Model/acmodel.hxx>
102 #include <AIModel/submodel.hxx>
103 #include <AIModel/AIManager.hxx>
104 #include <Navaids/navdb.hxx>
105 #include <Navaids/navlist.hxx>
106 #include <Navaids/fix.hxx>
107 #include <Navaids/fixlist.hxx>
108 #include <Scenery/scenery.hxx>
109 #include <Scenery/tilemgr.hxx>
110 #include <Scripting/NasalSys.hxx>
111 #include <Sound/fg_fx.hxx>
112 #include <Sound/beacon.hxx>
113 #include <Sound/morse.hxx>
114 #include <Sound/voice.hxx>
115 #include <Systems/system_mgr.hxx>
116 #include <Time/light.hxx>
117 #include <Time/sunsolver.hxx>
118 #include <Time/tmp.hxx>
119 #include <Traffic/TrafficMgr.hxx>
120 #include <MultiPlayer/multiplaymgr.hxx>
122 #include <Environment/environment_mgr.hxx>
123 #include <Environment/ridge_lift.hxx>
125 #include "fg_init.hxx"
127 #include "fg_commands.hxx"
128 #include "fg_props.hxx"
129 #include "options.hxx"
130 #include "globals.hxx"
131 #include "logger.hxx"
132 #include "renderer.hxx"
133 #include "viewmgr.hxx"
135 #include "ATCDCL/commlist.hxx"
138 # include <CoreFoundation/CoreFoundation.h>
142 using namespace boost::algorithm;
145 extern const char *default_root;
149 // Scan the command line options for the specified option and return
151 static string fgScanForOption( const string& option, int argc, char **argv ) {
154 if (hostname == NULL)
157 gethostname(_hostname, 256);
158 hostname = strdup(_hostname);
159 free_hostname = true;
162 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
164 int len = option.length();
167 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
169 string arg = argv[i];
170 if ( arg.find( option ) == 0 ) {
171 return arg.substr( len );
181 // Scan the user config files for the specified option and return
183 static string fgScanForOption( const string& option, const string& path ) {
184 sg_gzifstream in( path );
185 if ( !in.is_open() ) {
189 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
191 int len = option.length();
194 while ( ! in.eof() ) {
196 getline( in, line, '\n' );
198 // catch extraneous (DOS) line ending character
199 if ( line[line.length() - 1] < 32 ) {
200 line = line.substr( 0, line.length()-1 );
203 if ( line.find( option ) == 0 ) {
204 return line.substr( len );
213 // Scan the user config files for the specified option and return
215 static string fgScanForOption( const string& option ) {
218 #if defined( unix ) || defined( __CYGWIN__ )
219 // Next check home directory for .fgfsrc.hostname file
221 if ( homedir != NULL ) {
222 SGPath config( homedir );
223 config.append( ".fgfsrc" );
224 config.concat( "." );
225 config.concat( hostname );
226 arg = fgScanForOption( option, config.str() );
231 // Next check home directory for .fgfsrc file
233 if ( homedir != NULL ) {
234 SGPath config( homedir );
235 config.append( ".fgfsrc" );
236 arg = fgScanForOption( option, config.str() );
241 // Check for $fg_root/system.fgfsrc
242 SGPath config( globals->get_fg_root() );
243 config.append( "system.fgfsrc" );
244 arg = fgScanForOption( option, config.str() );
251 // Read in configuration (files and command line options) but only set
253 bool fgInitFGRoot ( int argc, char **argv ) {
256 // First parse command line options looking for --fg-root=, this
257 // will override anything specified in a config file
258 root = fgScanForOption( "--fg-root=", argc, argv);
260 // Check in one of the user configuration files.
262 root = fgScanForOption( "--fg-root=" );
264 // Next check if fg-root is set as an env variable
265 if ( root.empty() ) {
266 char *envp = ::getenv( "FG_ROOT" );
267 if ( envp != NULL ) {
272 // Otherwise, default to a random compiled-in location if we can't
273 // find fg-root any other way.
274 if ( root.empty() ) {
275 #if defined( __CYGWIN__ )
276 root = "/FlightGear";
277 #elif defined( WIN32 )
278 root = "\\FlightGear";
279 #elif defined(__APPLE__)
281 The following code looks for the base package inside the application
282 bundle, in the standard Contents/Resources location.
284 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
286 // look for a 'data' subdir
287 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
289 // now convert down to a path, and the a c-string
290 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
291 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
293 CFRelease(resourcesUrl);
301 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
302 globals->set_fg_root(root);
308 // Read in configuration (files and command line options) but only set
310 bool fgInitFGAircraft ( int argc, char **argv ) {
313 // First parse command line options looking for --aircraft=, this
314 // will override anything specified in a config file
315 aircraft = fgScanForOption( "--aircraft=", argc, argv );
316 if ( aircraft.empty() ) {
317 // check synonym option
318 aircraft = fgScanForOption( "--vehicle=", argc, argv );
321 // Check in one of the user configuration files.
322 if ( aircraft.empty() ) {
323 aircraft = fgScanForOption( "--aircraft=" );
325 if ( aircraft.empty() ) {
326 aircraft = fgScanForOption( "--vehicle=" );
329 // if an aircraft was specified, set the property name
330 if ( !aircraft.empty() ) {
331 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
332 fgSetString("/sim/aircraft", aircraft.c_str() );
334 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
341 // Return the current base package version
342 string fgBasePackageVersion() {
343 SGPath base_path( globals->get_fg_root() );
344 base_path.append("version");
346 sg_gzifstream in( base_path.str() );
347 if ( !in.is_open() ) {
348 SGPath old_path( globals->get_fg_root() );
349 old_path.append( "Thanks" );
350 sg_gzifstream old( old_path.str() );
351 if ( !old.is_open() ) {
354 return "[old version]";
365 // Initialize the localization
366 SGPropertyNode *fgInitLocale(const char *language) {
367 SGPropertyNode *c_node = NULL, *d_node = NULL;
368 SGPropertyNode *intl = fgGetNode("/sim/intl");
370 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
372 // localization not defined
377 // Select the proper language from the list
379 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
380 for (unsigned int i = 0; i < locale.size(); i++) {
382 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
383 for (unsigned int j = 0; j < lang.size(); j++) {
385 if (!strcmp(lang[j]->getStringValue(), language)) {
394 d_node = intl->getChild("locale");
398 // Check for localized font
399 SGPropertyNode *font_n = c_node->getNode("font", true);
400 if ( !strcmp(font_n->getStringValue(), "") )
401 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
405 // Load the default strings
407 SGPath d_path( globals->get_fg_root() );
409 const char *d_path_str = d_node->getStringValue("strings");
411 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
415 d_path.append(d_path_str);
416 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
418 SGPropertyNode *strings = c_node->getNode("strings");
420 readProperties(d_path.str(), strings);
421 } catch (const sg_exception &) {
422 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
427 // Load the language specific strings
429 if (c_node != d_node) {
430 SGPath c_path( globals->get_fg_root() );
432 const char *c_path_str = c_node->getStringValue("strings");
434 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
438 c_path.append(c_path_str);
439 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
442 readProperties(c_path.str(), strings);
443 } catch (const sg_exception &) {
444 SG_LOG(SG_GENERAL, SG_ALERT,
445 "Unable to read the localized strings from " << c_path.str());
455 // Initialize the localization routines
456 bool fgDetectLanguage() {
457 const char *language = ::getenv("LANG");
459 if (language == NULL) {
460 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
464 SGPropertyNode *locale = fgInitLocale(language);
466 SG_LOG(SG_GENERAL, SG_ALERT,
467 "No internationalization settings specified in preferences.xml" );
472 globals->set_locale( locale );
477 // Attempt to locate and parse the various non-XML config files in order
478 // from least precidence to greatest precidence
480 do_options (int argc, char ** argv)
482 // Check for $fg_root/system.fgfsrc
483 SGPath config( globals->get_fg_root() );
484 config.append( "system.fgfsrc" );
485 fgParseOptions(config.str());
487 #if defined( unix ) || defined( __CYGWIN__ )
488 config.concat( "." );
489 config.concat( hostname );
490 fgParseOptions(config.str());
493 // Check for ~/.fgfsrc
494 if ( homedir != NULL ) {
495 config.set( homedir );
496 config.append( ".fgfsrc" );
497 fgParseOptions(config.str());
500 #if defined( unix ) || defined( __CYGWIN__ )
501 // Check for ~/.fgfsrc.hostname
502 config.concat( "." );
503 config.concat( hostname );
504 fgParseOptions(config.str());
507 // Parse remaining command line options
508 // These will override anything specified in a config file
509 fgParseArgs(argc, argv);
513 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
514 SGPropertyNode *cache, int depth = 0 )
516 const int MAXDEPTH = 1;
519 ulDir *dirp = ulOpenDir(path.str().c_str());
521 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
526 while ((dire = ulReadDir(dirp)) != NULL) {
528 if (depth > MAXDEPTH)
531 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
532 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
536 next.append(dire->d_name);
538 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
539 if ( ! result.empty() )
543 int len = strlen(dire->d_name);
544 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
550 if (!cache->getChild("aircraft", i++, false))
553 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
555 n = entry->getNode("file", true);
556 n->setStringValue(dire->d_name);
557 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
559 n = entry->getNode("path", true);
560 n->setStringValue(path.str().c_str());
561 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
563 if ( boost::equals(dire->d_name, aircraft.c_str(), is_iequal()) ) {
575 // Read in configuration (file and command line)
576 bool fgInitConfig ( int argc, char **argv ) {
578 // First, set some sane default values
581 // Read global preferences from $FG_ROOT/preferences.xml
582 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
583 fgLoadProps("preferences.xml", globals->get_props());
584 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
586 // Detect the required language as early as possible
587 if ( !fgDetectLanguage() ) {
591 SGPropertyNode autosave;
592 #if defined( _MSC_VER ) || defined( __MINGW32__ )
593 char *envp = ::getenv( "APPDATA" );
595 SGPath config( envp );
596 config.append( "flightgear.org" );
598 if ( homedir != NULL ) {
599 SGPath config( homedir );
600 config.append( ".fgfs" );
602 const char *fg_home = getenv("FG_HOME");
606 SGPath home_export(config.str());
607 home_export.append("Export/dummy");
608 home_export.create_dir(0777);
610 // Set /sim/fg-home and don't allow malign code to override it until
611 // Nasal security is set up. Use FG_HOME if necessary.
612 SGPropertyNode *home = fgGetNode("/sim", true);
613 home->removeChild("fg-home", 0, false);
614 home = home->getChild("fg-home", 0, true);
615 home->setStringValue(config.c_str());
616 home->setAttribute(SGPropertyNode::WRITE, false);
618 config.append( "autosave.xml" );
619 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
621 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
623 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
625 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
627 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
630 // Scan user config files and command line for a specified aircraft.
631 fgInitFGAircraft(argc, argv);
633 string aircraft = fgGetString( "/sim/aircraft", "" );
634 if ( aircraft.size() > 0 ) {
635 SGPath aircraft_search( globals->get_fg_root() );
636 aircraft_search.append( "Aircraft" );
638 string aircraft_set = aircraft + "-set.xml";
641 // check if the *-set.xml file is already in the cache
642 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
643 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
644 for (unsigned int i = 0; i < cache.size(); i++) {
645 const char *name = cache[i]->getStringValue("file", "");
646 if (boost::equals(aircraft_set, name, is_iequal())) {
647 const char *path = cache[i]->getStringValue("path", "");
657 if (result.empty()) {
658 // prepare cache for rescan
659 SGPropertyNode *n = cache_root->getNode("fg-root", true);
660 n->setStringValue(globals->get_fg_root().c_str());
661 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
662 cache_root->removeChildren("aircraft");
664 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
667 if ( !result.empty() ) {
668 fgSetString( "/sim/aircraft-dir", result.c_str() );
669 SGPath full_name( result );
670 full_name.append( aircraft_set );
672 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
673 << " from " << full_name.str());
675 readProperties( full_name.str(), globals->get_props() );
676 } catch ( const sg_exception &e ) {
677 string message = "Error reading default aircraft: ";
678 message += e.getFormattedMessage();
679 SG_LOG(SG_INPUT, SG_ALERT, message);
683 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
689 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
692 copyProperties(&autosave, globals->get_props());
694 // parse options after loading aircraft to ensure any user
695 // overrides of defaults are honored.
696 do_options(argc, argv);
701 // Set current tower position lon/lat given an airport id
702 static bool fgSetTowerPosFromAirportID( const string& id) {
703 const FGAirport *a = fgFindAirportID( id);
705 SGGeod tower = a->getTowerLocation();
706 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
707 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
708 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
716 struct FGTowerLocationListener : SGPropertyChangeListener {
717 void valueChanged(SGPropertyNode* node) {
718 const string id(node->getStringValue());
719 fgSetTowerPosFromAirportID(id);
723 void fgInitTowerLocationListener() {
724 fgGetNode("/sim/tower/airport-id", true)
725 ->addChangeListener( new FGTowerLocationListener(), true );
728 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
730 SGGeod startPos(aStartPos);
731 if (aTargetHeading == HUGE_VAL) {
732 aTargetHeading = aHeading;
735 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
736 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
737 offsetDistance *= SG_NM_TO_METER;
738 double offsetAzimuth = aHeading;
739 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
740 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
741 aHeading = aTargetHeading;
746 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
751 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
752 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
753 fgSetDouble("/sim/presets/heading-deg", aHeading );
755 // other code depends on the actual values being set ...
756 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
757 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
758 fgSetDouble("/orientation/heading-deg", aHeading );
761 // Set current_options lon/lat given an airport id and heading (degrees)
762 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
766 // set initial position from runway and heading
767 SG_LOG( SG_GENERAL, SG_INFO,
768 "Attempting to set starting position from airport code "
769 << id << " heading " << tgt_hdg );
771 const FGAirport* apt = fgFindAirportID(id);
772 if (!apt) return false;
773 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
774 fgSetString("/sim/atc/runway", r->ident().c_str());
776 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
777 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
781 // Set current_options lon/lat given an airport id and parkig position name
782 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
786 // can't see an easy way around this const_cast at the moment
787 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
789 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
792 FGAirportDynamics* dcs = apt->getDynamics();
794 SG_LOG( SG_GENERAL, SG_ALERT,
795 "Failed to find parking position " << parkpos <<
796 " at airport " << id );
800 int park_index = dcs->getNrOfParkings() - 1;
801 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
802 if (park_index < 0) {
803 SG_LOG( SG_GENERAL, SG_ALERT,
804 "Failed to find parking position " << parkpos <<
805 " at airport " << id );
808 FGParking* parking = dcs->getParking(park_index);
810 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
811 parking->getHeading());
816 // Set current_options lon/lat given an airport id and runway number
817 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
821 // set initial position from airport and runway number
822 SG_LOG( SG_GENERAL, SG_INFO,
823 "Attempting to set starting position for "
824 << id << ":" << rwy );
826 const FGAirport* apt = fgFindAirportID(id);
828 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
832 if (!apt->hasRunwayWithIdent(rwy)) {
833 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
834 "Failed to find runway " << rwy <<
835 " at airport " << id << ". Using default runway." );
839 FGRunway* r(apt->getRunwayByIdent(rwy));
840 fgSetString("/sim/atc/runway", r->ident().c_str());
841 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
842 fgApplyStartOffset(startPos, r->headingDeg());
847 static void fgSetDistOrAltFromGlideSlope() {
848 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
849 string apt_id = fgGetString("/sim/presets/airport-id");
850 double gs = fgGetDouble("/sim/presets/glideslope-deg")
851 * SG_DEGREES_TO_RADIANS ;
852 double od = fgGetDouble("/sim/presets/offset-distance-nm");
853 double alt = fgGetDouble("/sim/presets/altitude-ft");
855 double apt_elev = 0.0;
856 if ( ! apt_id.empty() ) {
857 apt_elev = fgGetAirportElev( apt_id );
858 if ( apt_elev < -9990.0 ) {
865 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
866 // set altitude from glideslope and offset-distance
867 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
868 alt = fabs(od*tan(gs)) + apt_elev;
869 fgSetDouble("/sim/presets/altitude-ft", alt);
870 fgSetBool("/sim/presets/onground", false);
871 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
873 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
874 // set offset-distance from glideslope and altitude
875 od = (alt - apt_elev) / tan(gs);
876 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
877 fgSetDouble("/sim/presets/offset-distance-nm", od);
878 fgSetBool("/sim/presets/onground", false);
879 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
881 } else if( fabs(gs) > 0.01 ) {
882 SG_LOG( SG_GENERAL, SG_ALERT,
883 "Glideslope given but not altitude or offset-distance." );
884 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
885 fgSetDouble("/sim/presets/glideslope-deg", 0);
886 fgSetBool("/sim/presets/onground", true);
891 // Set current_options lon/lat given an airport id and heading (degrees)
892 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
894 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
897 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
898 << id << ":" << freq );
902 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
906 // Set current_options lon/lat given an aircraft carrier id
907 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
909 // set initial position from runway and heading
913 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
914 double lon = geodPos.getLongitudeDeg();
915 double lat = geodPos.getLatitudeDeg();
916 double alt = geodPos.getElevationFt();
918 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
919 << carrier << " at lat = " << lat << ", lon = " << lon
920 << ", alt = " << alt << ", heading = " << heading);
922 fgSetDouble("/sim/presets/longitude-deg", lon);
923 fgSetDouble("/sim/presets/latitude-deg", lat);
924 fgSetDouble("/sim/presets/altitude-ft", alt);
925 fgSetDouble("/sim/presets/heading-deg", heading);
926 fgSetDouble("/position/longitude-deg", lon);
927 fgSetDouble("/position/latitude-deg", lat);
928 fgSetDouble("/position/altitude-ft", alt);
929 fgSetDouble("/orientation/heading-deg", heading);
931 fgSetString("/sim/presets/speed-set", "UVW");
932 fgSetDouble("/velocities/uBody-fps", uvw(0));
933 fgSetDouble("/velocities/vBody-fps", uvw(1));
934 fgSetDouble("/velocities/wBody-fps", uvw(2));
935 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
936 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
937 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
939 fgSetBool("/sim/presets/onground", true);
943 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
949 // Set current_options lon/lat given an airport id and heading (degrees)
950 static bool fgSetPosFromFix( const string& id )
952 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
953 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
955 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
959 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
964 * Initialize vor/ndb/ils/fix list management and query systems (as
965 * well as simple airport db list)
970 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
972 SGPath aptdb( globals->get_fg_root() );
973 aptdb.append( "Airports/apt.dat" );
975 SGPath p_metar( globals->get_fg_root() );
976 p_metar.append( "Airports/metar.dat" );
978 // Initialise the frequency search map BEFORE reading
979 // the airport database:
980 current_commlist = new FGCommList;
981 current_commlist->init( globals->get_fg_root() );
982 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
984 FGNavList *navlist = new FGNavList;
985 FGNavList *loclist = new FGNavList;
986 FGNavList *gslist = new FGNavList;
987 FGNavList *dmelist = new FGNavList;
988 FGNavList *tacanlist = new FGNavList;
989 FGNavList *carrierlist = new FGNavList;
990 FGTACANList *channellist = new FGTACANList;
992 globals->set_navlist( navlist );
993 globals->set_loclist( loclist );
994 globals->set_gslist( gslist );
995 globals->set_dmelist( dmelist );
996 globals->set_tacanlist( tacanlist );
997 globals->set_carrierlist( carrierlist );
998 globals->set_channellist( channellist );
1000 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1001 SG_LOG( SG_GENERAL, SG_ALERT,
1002 "Problems loading one or more navigational database" );
1005 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1006 SGPath p_fix( globals->get_fg_root() );
1007 p_fix.append( "Navaids/fix.dat" );
1009 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1011 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1012 SGPath p_awy( globals->get_fg_root() );
1013 p_awy.append( "Navaids/awy.dat" );
1014 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1015 //cerr << "Loading Airways" << endl;
1016 awyNet->load (p_awy );
1018 //cerr << "initializing airways" << endl;
1019 globals->set_airwaynet( awyNet );
1025 // Set the initial position based on presets (or defaults)
1026 bool fgInitPosition() {
1027 // cout << "fgInitPosition()" << endl;
1028 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1029 * SG_DEGREES_TO_RADIANS ;
1030 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1031 double alt = fgGetDouble("/sim/presets/altitude-ft");
1033 bool set_pos = false;
1035 // If glideslope is specified, then calculate offset-distance or
1036 // altitude relative to glide slope if either of those was not
1038 if ( fabs( gs ) > 0.01 ) {
1039 fgSetDistOrAltFromGlideSlope();
1043 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1044 // If not, check for an airport-id and use that.
1045 // If not, default to the middle of the KSFO field.
1046 // The default values for lon/lat are deliberately out of range
1047 // so that the airport-id can take effect; valid lon/lat will
1048 // override airport-id, however.
1049 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1050 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1051 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1052 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1057 string apt = fgGetString("/sim/presets/airport-id");
1058 string rwy_no = fgGetString("/sim/presets/runway");
1059 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1060 string vor = fgGetString("/sim/presets/vor-id");
1061 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1062 string ndb = fgGetString("/sim/presets/ndb-id");
1063 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1064 string carrier = fgGetString("/sim/presets/carrier");
1065 string parkpos = fgGetString("/sim/presets/parkpos");
1066 string fix = fgGetString("/sim/presets/fix");
1067 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1068 double hdg = hdg_preset->getDoubleValue();
1070 // save some start parameters, so that we can later say what the
1071 // user really requested. TODO generalize that and move it to options.cxx
1072 static bool start_options_saved = false;
1073 if (!start_options_saved) {
1074 start_options_saved = true;
1075 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1077 opt->setDoubleValue("latitude-deg", lat_deg);
1078 opt->setDoubleValue("longitude-deg", lon_deg);
1079 opt->setDoubleValue("heading-deg", hdg);
1080 opt->setStringValue("airport", apt.c_str());
1081 opt->setStringValue("runway", rwy_no.c_str());
1085 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1087 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1088 // An airport + parking position is requested
1089 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1090 // set tower position
1091 fgSetString("/sim/tower/airport-id", apt.c_str());
1096 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1097 // An airport + runway is requested
1098 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1099 // set tower position (a little off the heading for single
1101 fgSetString("/sim/tower/airport-id", apt.c_str());
1106 if ( !set_pos && !apt.empty() ) {
1107 // An airport is requested (find runway closest to hdg)
1108 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1109 // set tower position (a little off the heading for single
1111 fgSetString("/sim/tower/airport-id", apt.c_str());
1116 if (hdg_preset->getDoubleValue() > 9990.0)
1117 hdg_preset->setDoubleValue(hdg);
1119 if ( !set_pos && !vor.empty() ) {
1120 // a VOR is requested
1121 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1126 if ( !set_pos && !ndb.empty() ) {
1127 // an NDB is requested
1128 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1133 if ( !set_pos && !carrier.empty() ) {
1134 // an aircraft carrier is requested
1135 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1140 if ( !set_pos && !fix.empty() ) {
1141 // a Fix is requested
1142 if ( fgSetPosFromFix( fix ) ) {
1148 // No lon/lat specified, no airport specified, default to
1149 // middle of KSFO field.
1150 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1151 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1154 fgSetDouble( "/position/longitude-deg",
1155 fgGetDouble("/sim/presets/longitude-deg") );
1156 fgSetDouble( "/position/latitude-deg",
1157 fgGetDouble("/sim/presets/latitude-deg") );
1158 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1160 // determine if this should be an on-ground or in-air start
1161 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1162 fgSetBool("/sim/presets/onground", false);
1164 fgSetBool("/sim/presets/onground", true);
1171 // General house keeping initializations
1172 bool fgInitGeneral() {
1175 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1176 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1178 root = globals->get_fg_root();
1179 if ( ! root.length() ) {
1180 // No root path set? Then bail ...
1181 SG_LOG( SG_GENERAL, SG_ALERT,
1182 "Cannot continue without a path to the base package "
1183 << "being defined." );
1186 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1188 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1190 char buf[512], *cwd = getcwd(buf, 511);
1192 SGPropertyNode *curr = fgGetNode("/sim", true);
1193 curr->removeChild("fg-current", 0, false);
1194 curr = curr->getChild("fg-current", 0, true);
1195 curr->setStringValue(cwd ? cwd : "");
1196 curr->setAttribute(SGPropertyNode::WRITE, false);
1198 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1199 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1204 // Initialize the flight model subsystem. This just creates the
1205 // object. The actual fdm initialization is delayed until we get a
1206 // proper scenery elevation hit. This is checked for in main.cxx
1210 if ( cur_fdm_state ) {
1211 delete cur_fdm_state;
1215 double dt = 1.0 / fgGetInt("/sim/model-hz");
1216 string model = fgGetString("/sim/flight-model");
1218 if ( model == "larcsim" ) {
1219 cur_fdm_state = new FGLaRCsim( dt );
1220 } else if ( model == "jsb" ) {
1221 cur_fdm_state = new FGJSBsim( dt );
1223 } else if ( model == "ada" ) {
1224 cur_fdm_state = new FGADA( dt );
1225 } else if ( model == "acms" ) {
1226 cur_fdm_state = new FGACMS( dt );
1227 } else if ( model == "balloon" ) {
1228 cur_fdm_state = new FGBalloonSim( dt );
1229 } else if ( model == "magic" ) {
1230 cur_fdm_state = new FGMagicCarpet( dt );
1232 } else if ( model == "ufo" ) {
1233 cur_fdm_state = new FGUFO( dt );
1234 } else if ( model == "external" ) {
1235 // external is a synonym for "--fdm=null" and is
1236 // maintained here for backwards compatibility
1237 cur_fdm_state = new FGNullFDM( dt );
1238 } else if ( model.find("network") == 0 ) {
1239 string host = "localhost";
1243 string net_options = model.substr(8);
1244 string::size_type begin, end;
1247 end = net_options.find( ",", begin );
1248 if ( end != string::npos ) {
1249 host = net_options.substr(begin, end - begin);
1253 end = net_options.find( ",", begin );
1254 if ( end != string::npos ) {
1255 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1259 end = net_options.find( ",", begin );
1260 if ( end != string::npos ) {
1261 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1265 end = net_options.find( ",", begin );
1266 if ( end != string::npos ) {
1267 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1270 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1271 } else if ( model.find("pipe") == 0 ) {
1272 // /* old */ string pipe_path = model.substr(5);
1273 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1274 string pipe_path = "";
1275 string pipe_protocol = "";
1276 string pipe_options = model.substr(5);
1277 string::size_type begin, end;
1280 end = pipe_options.find( ",", begin );
1281 if ( end != string::npos ) {
1282 pipe_path = pipe_options.substr(begin, end - begin);
1285 // protocol (last option)
1286 pipe_protocol = pipe_options.substr(begin);
1287 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1288 } else if ( model == "null" ) {
1289 cur_fdm_state = new FGNullFDM( dt );
1290 } else if ( model == "yasim" ) {
1291 cur_fdm_state = new YASim( dt );
1293 throw sg_exception(string("Unrecognized flight model '") + model
1294 + "', cannot init flight dynamics model.");
1298 // Initialize view parameters
1300 // force update of model so that viewer can get some data...
1301 globals->get_aircraft_model()->update(0);
1302 // run update for current view so that data is current...
1303 globals->get_viewmgr()->update(0);
1307 SGTime *fgInitTime() {
1309 static const SGPropertyNode *longitude
1310 = fgGetNode("/position/longitude-deg");
1311 static const SGPropertyNode *latitude
1312 = fgGetNode("/position/latitude-deg");
1313 static const SGPropertyNode *cur_time_override
1314 = fgGetNode("/sim/time/cur-time-override", true);
1316 SGPath zone( globals->get_fg_root() );
1317 zone.append( "Timezone" );
1318 SGTime *t = new SGTime( longitude->getDoubleValue()
1319 * SGD_DEGREES_TO_RADIANS,
1320 latitude->getDoubleValue()
1321 * SGD_DEGREES_TO_RADIANS,
1323 cur_time_override->getLongValue() );
1325 globals->set_warp_delta( 0 );
1327 t->update( 0.0, 0.0,
1328 cur_time_override->getLongValue(),
1329 globals->get_warp() );
1335 // set up a time offset (aka warp) if one is specified
1336 void fgInitTimeOffset() {
1337 static const SGPropertyNode *longitude
1338 = fgGetNode("/position/longitude-deg");
1339 static const SGPropertyNode *latitude
1340 = fgGetNode("/position/latitude-deg");
1341 static const SGPropertyNode *cur_time_override
1342 = fgGetNode("/sim/time/cur-time-override", true);
1344 // Handle potential user specified time offsets
1345 int orig_warp = globals->get_warp();
1346 SGTime *t = globals->get_time_params();
1347 time_t cur_time = t->get_cur_time();
1348 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1349 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1350 time_t aircraftLocalTime =
1351 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1353 // Okay, we now have several possible scenarios
1354 int offset = fgGetInt("/sim/startup/time-offset");
1355 string offset_type = fgGetString("/sim/startup/time-offset-type");
1358 if ( offset_type == "real" ) {
1360 } else if ( offset_type == "dawn" ) {
1361 warp = fgTimeSecondsUntilSunAngle( cur_time,
1362 longitude->getDoubleValue()
1363 * SGD_DEGREES_TO_RADIANS,
1364 latitude->getDoubleValue()
1365 * SGD_DEGREES_TO_RADIANS,
1367 } else if ( offset_type == "morning" ) {
1368 warp = fgTimeSecondsUntilSunAngle( cur_time,
1369 longitude->getDoubleValue()
1370 * SGD_DEGREES_TO_RADIANS,
1371 latitude->getDoubleValue()
1372 * SGD_DEGREES_TO_RADIANS,
1374 } else if ( offset_type == "noon" ) {
1375 warp = fgTimeSecondsUntilSunAngle( cur_time,
1376 longitude->getDoubleValue()
1377 * SGD_DEGREES_TO_RADIANS,
1378 latitude->getDoubleValue()
1379 * SGD_DEGREES_TO_RADIANS,
1381 } else if ( offset_type == "afternoon" ) {
1382 warp = fgTimeSecondsUntilSunAngle( cur_time,
1383 longitude->getDoubleValue()
1384 * SGD_DEGREES_TO_RADIANS,
1385 latitude->getDoubleValue()
1386 * SGD_DEGREES_TO_RADIANS,
1388 } else if ( offset_type == "dusk" ) {
1389 warp = fgTimeSecondsUntilSunAngle( cur_time,
1390 longitude->getDoubleValue()
1391 * SGD_DEGREES_TO_RADIANS,
1392 latitude->getDoubleValue()
1393 * SGD_DEGREES_TO_RADIANS,
1395 } else if ( offset_type == "evening" ) {
1396 warp = fgTimeSecondsUntilSunAngle( cur_time,
1397 longitude->getDoubleValue()
1398 * SGD_DEGREES_TO_RADIANS,
1399 latitude->getDoubleValue()
1400 * SGD_DEGREES_TO_RADIANS,
1402 } else if ( offset_type == "midnight" ) {
1403 warp = fgTimeSecondsUntilSunAngle( cur_time,
1404 longitude->getDoubleValue()
1405 * SGD_DEGREES_TO_RADIANS,
1406 latitude->getDoubleValue()
1407 * SGD_DEGREES_TO_RADIANS,
1409 } else if ( offset_type == "system-offset" ) {
1412 } else if ( offset_type == "gmt-offset" ) {
1413 warp = offset - (currGMT - systemLocalTime);
1415 } else if ( offset_type == "latitude-offset" ) {
1416 warp = offset - (aircraftLocalTime - systemLocalTime);
1418 } else if ( offset_type == "system" ) {
1419 warp = offset - (systemLocalTime - currGMT) - cur_time;
1420 } else if ( offset_type == "gmt" ) {
1421 warp = offset - cur_time;
1422 } else if ( offset_type == "latitude" ) {
1423 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1425 SG_LOG( SG_GENERAL, SG_ALERT,
1426 "FG_TIME::Unsupported offset type " << offset_type );
1429 globals->set_warp( orig_warp + warp );
1430 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1431 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1432 cur_time_override->getLongValue(),
1433 globals->get_warp() );
1435 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1436 << globals->get_warp() );
1440 // This is the top level init routine which calls all the other
1441 // initialization routines. If you are adding a subsystem to flight
1442 // gear, its initialization call should located in this routine.
1443 // Returns non-zero if a problem encountered.
1444 bool fgInitSubsystems() {
1445 // static const SGPropertyNode *longitude
1446 // = fgGetNode("/sim/presets/longitude-deg");
1447 // static const SGPropertyNode *latitude
1448 // = fgGetNode("/sim/presets/latitude-deg");
1449 // static const SGPropertyNode *altitude
1450 // = fgGetNode("/sim/presets/altitude-ft");
1452 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1453 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1455 ////////////////////////////////////////////////////////////////////
1456 // Initialize the event manager subsystem.
1457 ////////////////////////////////////////////////////////////////////
1459 globals->get_event_mgr()->init();
1460 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1462 ////////////////////////////////////////////////////////////////////
1463 // Initialize the property interpolator subsystem. Put into the INIT
1464 // group because the "nasal" subsystem may need it at GENERAL take-down.
1465 ////////////////////////////////////////////////////////////////////
1466 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1469 ////////////////////////////////////////////////////////////////////
1470 // Add the FlightGear property utilities.
1471 ////////////////////////////////////////////////////////////////////
1472 globals->add_subsystem("properties", new FGProperties);
1474 ////////////////////////////////////////////////////////////////////
1475 // Initialize the material property subsystem.
1476 ////////////////////////////////////////////////////////////////////
1478 SGPath mpath( globals->get_fg_root() );
1479 mpath.append( "materials.xml" );
1480 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1481 globals->get_props()) ) {
1482 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1487 ////////////////////////////////////////////////////////////////////
1488 // Initialize the scenery management subsystem.
1489 ////////////////////////////////////////////////////////////////////
1491 if ( globals->get_tile_mgr()->init() ) {
1492 // Load the local scenery data
1493 double visibility_meters = fgGetDouble("/environment/visibility-m");
1495 globals->get_tile_mgr()->update( visibility_meters );
1497 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1501 globals->get_scenery()->get_scene_graph()
1502 ->addChild(simgear::Particles::getCommonRoot());
1503 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1505 ////////////////////////////////////////////////////////////////////
1506 // Initialize the flight model subsystem.
1507 ////////////////////////////////////////////////////////////////////
1511 // allocates structures so must happen before any of the flight
1512 // model or control parameters are set
1513 fgAircraftInit(); // In the future this might not be the case.
1516 ////////////////////////////////////////////////////////////////////
1517 // Initialize the weather subsystem.
1518 ////////////////////////////////////////////////////////////////////
1520 // Initialize the weather modeling subsystem
1521 globals->add_subsystem("environment", new FGEnvironmentMgr);
1523 ////////////////////////////////////////////////////////////////////
1524 // Initialize the ridge lift simulation.
1525 ////////////////////////////////////////////////////////////////////
1527 // Initialize the ridgelift subsystem
1528 globals->add_subsystem("ridgelift", new FGRidgeLift);
1531 ////////////////////////////////////////////////////////////////////
1532 // Initialize the aircraft systems and instrumentation (before the
1534 ////////////////////////////////////////////////////////////////////
1536 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1537 globals->add_subsystem("systems", new FGSystemMgr);
1539 ////////////////////////////////////////////////////////////////////
1540 // Initialize the XML Autopilot subsystem.
1541 ////////////////////////////////////////////////////////////////////
1543 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1544 globals->add_subsystem( "route-manager", new FGRouteMgr );
1545 globals->add_subsystem( "autobrake", new FGAutoBrake );
1547 ////////////////////////////////////////////////////////////////////
1548 // Initialize the view manager subsystem.
1549 ////////////////////////////////////////////////////////////////////
1553 ////////////////////////////////////////////////////////////////////
1554 // Initialize the Input-Output subsystem
1555 ////////////////////////////////////////////////////////////////////
1556 globals->add_subsystem( "io", new FGIO );
1558 ////////////////////////////////////////////////////////////////////
1559 // Create and register the logger.
1560 ////////////////////////////////////////////////////////////////////
1562 globals->add_subsystem("logger", new FGLogger);
1564 ////////////////////////////////////////////////////////////////////
1565 // Create and register the XML GUI.
1566 ////////////////////////////////////////////////////////////////////
1568 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1571 ////////////////////////////////////////////////////////////////////
1572 // Initialize the local time subsystem.
1573 ////////////////////////////////////////////////////////////////////
1575 // update the current timezone each 30 minutes
1576 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1577 &fgUpdateLocalTime, 30*60 );
1578 fgInitTimeOffset(); // the environment subsystem needs this
1581 ////////////////////////////////////////////////////////////////////
1582 // Initialize the lighting subsystem.
1583 ////////////////////////////////////////////////////////////////////
1585 globals->add_subsystem("lighting", new FGLight);
1587 //////////////////////////////////////////////////////////////////////
1588 // Initialize the 2D cloud subsystem.
1589 ////////////////////////////////////////////////////////////////////
1590 fgGetBool("/sim/rendering/bump-mapping", false);
1592 #ifdef ENABLE_AUDIO_SUPPORT
1593 ////////////////////////////////////////////////////////////////////
1594 // Initialize the sound subsystem.
1595 ////////////////////////////////////////////////////////////////////
1597 init_volume = fgGetFloat("/sim/sound/volume");
1598 fgSetFloat("/sim/sound/volume", 0.0f);
1599 globals->set_soundmgr(new SGSoundMgr);
1600 globals->get_soundmgr()->init();
1601 globals->get_soundmgr()->bind();
1604 ////////////////////////////////////////////////////////////////////
1605 // Initialize the sound-effects subsystem.
1606 ////////////////////////////////////////////////////////////////////
1608 globals->add_subsystem("fx", new FGFX);
1609 globals->add_subsystem("voice", new FGVoiceMgr);
1612 ////////////////////////////////////////////////////////////////////
1613 // Initialise the ATC Manager
1614 ////////////////////////////////////////////////////////////////////
1616 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1617 globals->set_ATC_mgr(new FGATCMgr);
1618 globals->get_ATC_mgr()->init();
1620 ////////////////////////////////////////////////////////////////////
1621 // Initialise the AI Manager
1622 ////////////////////////////////////////////////////////////////////
1624 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1625 globals->set_AI_mgr(new FGAIMgr);
1626 globals->get_AI_mgr()->init();
1628 ////////////////////////////////////////////////////////////////////
1629 // Initialise the AI Model Manager
1630 ////////////////////////////////////////////////////////////////////
1631 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1632 globals->add_subsystem("ai_model", new FGAIManager);
1633 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1636 // It's probably a good idea to initialize the top level traffic manager
1637 // After the AI and ATC systems have been initialized properly.
1638 // AI Traffic manager
1639 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1642 ////////////////////////////////////////////////////////////////////
1643 // Initialize the cockpit subsystem
1644 ////////////////////////////////////////////////////////////////////
1645 if( fgCockpitInit( ¤t_aircraft )) {
1646 // Cockpit initialized ok.
1648 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1653 ////////////////////////////////////////////////////////////////////
1654 // Add a new 2D panel.
1655 ////////////////////////////////////////////////////////////////////
1657 string panel_path = fgGetString("/sim/panel/path",
1658 "Panels/Default/default.xml");
1660 globals->set_current_panel( fgReadPanel(panel_path) );
1661 if (globals->get_current_panel() == 0) {
1662 SG_LOG( SG_INPUT, SG_ALERT,
1663 "Error reading new panel from " << panel_path );
1665 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1666 globals->get_current_panel()->init();
1667 globals->get_current_panel()->bind();
1671 ////////////////////////////////////////////////////////////////////
1672 // Initialize the controls subsystem.
1673 ////////////////////////////////////////////////////////////////////
1675 globals->get_controls()->init();
1676 globals->get_controls()->bind();
1679 ////////////////////////////////////////////////////////////////////
1680 // Initialize the input subsystem.
1681 ////////////////////////////////////////////////////////////////////
1683 globals->add_subsystem("input", new FGInput);
1686 ////////////////////////////////////////////////////////////////////
1687 // Initialize the replay subsystem
1688 ////////////////////////////////////////////////////////////////////
1689 globals->add_subsystem("replay", new FGReplay);
1691 ////////////////////////////////////////////////////////////////////
1692 // Bind and initialize subsystems.
1693 ////////////////////////////////////////////////////////////////////
1695 globals->get_subsystem_mgr()->bind();
1696 globals->get_subsystem_mgr()->init();
1698 ////////////////////////////////////////////////////////////////////
1699 // Initialize multiplayer subsystem
1700 ////////////////////////////////////////////////////////////////////
1702 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1703 globals->get_multiplayer_mgr()->init();
1705 ////////////////////////////////////////////////////////////////////////
1706 // Initialize the Nasal interpreter.
1707 // Do this last, so that the loaded scripts see initialized state
1708 ////////////////////////////////////////////////////////////////////////
1709 FGNasalSys* nasal = new FGNasalSys();
1710 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1713 // initialize methods that depend on other subsystems.
1714 globals->get_subsystem_mgr()->postinit();
1716 ////////////////////////////////////////////////////////////////////////
1717 // End of subsystem initialization.
1718 ////////////////////////////////////////////////////////////////////
1720 SG_LOG( SG_GENERAL, SG_INFO, endl);
1722 // Save the initial state for future
1724 globals->saveInitialState();
1730 void fgReInitSubsystems()
1732 // static const SGPropertyNode *longitude
1733 // = fgGetNode("/sim/presets/longitude-deg");
1734 // static const SGPropertyNode *latitude
1735 // = fgGetNode("/sim/presets/latitude-deg");
1736 static const SGPropertyNode *altitude
1737 = fgGetNode("/sim/presets/altitude-ft");
1738 static const SGPropertyNode *master_freeze
1739 = fgGetNode("/sim/freeze/master");
1741 SG_LOG( SG_GENERAL, SG_INFO,
1742 "fgReInitSubsystems(): /position/altitude = "
1743 << altitude->getDoubleValue() );
1745 bool freeze = master_freeze->getBoolValue();
1747 fgSetBool("/sim/freeze/master", true);
1749 fgSetBool("/sim/crashed", false);
1751 // Force reupdating the positions of the ai 3d models. They are used for
1752 // initializing ground level for the FDM.
1753 globals->get_subsystem("ai_model")->reinit();
1755 // Initialize the FDM
1758 // allocates structures so must happen before any of the flight
1759 // model or control parameters are set
1760 fgAircraftInit(); // In the future this might not be the case.
1762 // reload offsets from config defaults
1763 globals->get_viewmgr()->reinit();
1767 globals->get_controls()->reset_all();
1769 fgUpdateLocalTime();
1771 // re-init to proper time of day setting
1775 fgSetBool("/sim/freeze/master", false);
1777 fgSetBool("/sim/sceneryloaded",false);
1781 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1783 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1785 bool freeze = master_freeze->getBoolValue();
1787 master_freeze->setBoolValue(true);
1789 fgSetBool("/sim/signals/reinit", true);
1790 cur_fdm_state->unbind();
1792 // in case user has changed window size as
1793 // restoreInitialState() overwrites these
1794 int xsize = fgGetInt("/sim/startup/xsize");
1795 int ysize = fgGetInt("/sim/startup/ysize");
1797 // viewports also needs to be saved/restored as
1798 // restoreInitialState() overwrites these
1799 SGPropertyNode *guiNode = new SGPropertyNode;
1800 SGPropertyNode *cameraNode = new SGPropertyNode;
1801 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1802 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1803 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1805 globals->restoreInitialState();
1807 // update our position based on current presets
1810 // We don't know how to resize the window, so keep the last values
1811 // for xsize and ysize, and don't use the one set initially
1812 fgSetInt("/sim/startup/xsize", xsize);
1813 fgSetInt("/sim/startup/ysize", ysize);
1815 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1816 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1821 SGTime *t = globals->get_time_params();
1824 globals->set_time_params(t);
1826 fgReInitSubsystems();
1828 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1829 globals->get_renderer()->resize(xsize, ysize);
1830 fgSetBool("/sim/signals/reinit", false);
1833 master_freeze->setBoolValue(false);