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.
28 // For BC 5.01 this must be included before OpenGL includes.
29 #ifdef SG_MATH_EXCEPTION_CLASH
35 #include <string.h> // strcmp()
37 #if defined( unix ) || defined( __CYGWIN__ )
38 # include <unistd.h> // for gethostname()
41 // work around a stdc++ lib bug in some versions of linux, but doesn't
42 // seem to hurt to have this here for all versions of Linux.
44 # define _G_NO_EXTERN_TEMPLATES
47 #include <simgear/compiler.h>
51 #include <simgear/constants.h>
52 #include <simgear/debug/logstream.hxx>
53 #include <simgear/structure/exception.hxx>
54 #include <simgear/structure/event_mgr.hxx>
55 #include <simgear/math/point3d.hxx>
56 #include <simgear/math/polar3d.hxx>
57 #include <simgear/math/sg_geodesy.hxx>
58 #include <simgear/misc/sg_path.hxx>
59 #include <simgear/misc/interpolator.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #include <simgear/timing/sg_time.hxx>
62 #include <simgear/timing/lowleveltime.h>
64 #include <Aircraft/aircraft.hxx>
65 #include <Aircraft/replay.hxx>
66 #include <Airports/apt_loader.hxx>
67 #include <Airports/runways.hxx>
68 #include <Airports/simple.hxx>
69 #include <AIModel/AIManager.hxx>
70 #include <ATC/ATCmgr.hxx>
71 #include <ATC/AIMgr.hxx>
72 #include <Autopilot/route_mgr.hxx>
73 #include <Autopilot/xmlauto.hxx>
74 #include <Cockpit/cockpit.hxx>
75 #include <Cockpit/panel.hxx>
76 #include <Cockpit/panel_io.hxx>
78 #include <FDM/SP/ADA.hxx>
79 #include <FDM/SP/ACMS.hxx>
81 #include <FDM/Balloon.h>
82 #include <FDM/ExternalNet/ExternalNet.hxx>
83 #include <FDM/ExternalPipe/ExternalPipe.hxx>
84 #include <FDM/JSBSim/JSBSim.hxx>
85 #include <FDM/LaRCsim/LaRCsim.hxx>
86 #include <FDM/MagicCarpet.hxx>
87 #include <FDM/UFO.hxx>
88 #include <FDM/NullFDM.hxx>
89 #include <FDM/YASim/YASim.hxx>
90 #include <GUI/new_gui.hxx>
91 #include <Include/general.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <AIModel/submodel.hxx>
96 #include <AIModel/AIManager.hxx>
97 #include <Navaids/navdb.hxx>
98 #include <Navaids/navlist.hxx>
99 #include <Scenery/scenery.hxx>
100 #include <Scenery/tilemgr.hxx>
101 #include <Scripting/NasalSys.hxx>
102 #include <Sound/fg_fx.hxx>
103 #include <Sound/beacon.hxx>
104 #include <Sound/morse.hxx>
105 #include <Sound/voice.hxx>
106 #include <Systems/system_mgr.hxx>
107 #include <Time/light.hxx>
108 #include <Time/sunsolver.hxx>
109 #include <Time/tmp.hxx>
110 #include <Traffic/TrafficMgr.hxx>
111 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <Environment/environment_mgr.hxx>
115 #include "fg_init.hxx"
117 #include "fg_commands.hxx"
118 #include "fg_props.hxx"
119 #include "options.hxx"
120 #include "globals.hxx"
121 #include "logger.hxx"
122 #include "viewmgr.hxx"
125 #if defined(FX) && defined(XMESA)
126 #include <GL/xmesa.h>
129 SG_USING_STD(string);
133 extern const char *default_root;
137 // Scan the command line options for the specified option and return
139 static string fgScanForOption( const string& option, int argc, char **argv ) {
142 if (hostname == NULL)
145 gethostname(_hostname, 256);
146 hostname = strdup(_hostname);
147 free_hostname = true;
150 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
152 int len = option.length();
155 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
157 string arg = argv[i];
158 if ( arg.find( option ) == 0 ) {
159 return arg.substr( len );
169 // Scan the user config files for the specified option and return
171 static string fgScanForOption( const string& option, const string& path ) {
172 sg_gzifstream in( path );
173 if ( !in.is_open() ) {
177 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
179 int len = option.length();
183 while ( ! in.eof() ) {
186 while ( in.get(c) && c != '\0' ) {
191 #if defined( macintosh )
192 getline( in, line, '\r' );
194 getline( in, line, '\n' );
197 // catch extraneous (DOS) line ending character
198 if ( line[line.length() - 1] < 32 ) {
199 line = line.substr( 0, line.length()-1 );
202 if ( line.find( option ) == 0 ) {
203 return line.substr( len );
212 // Scan the user config files for the specified option and return
214 static string fgScanForOption( const string& option ) {
217 #if defined( unix ) || defined( __CYGWIN__ )
218 // Next check home directory for .fgfsrc.hostname file
220 if ( homedir != NULL ) {
221 SGPath config( homedir );
222 config.append( ".fgfsrc" );
223 config.concat( "." );
224 config.concat( hostname );
225 arg = fgScanForOption( option, config.str() );
230 // Next check home directory for .fgfsrc file
232 if ( homedir != NULL ) {
233 SGPath config( homedir );
234 config.append( ".fgfsrc" );
235 arg = fgScanForOption( option, config.str() );
240 // Check for $fg_root/system.fgfsrc
241 SGPath config( globals->get_fg_root() );
242 config.append( "system.fgfsrc" );
243 arg = fgScanForOption( option, config.str() );
250 // Read in configuration (files and command line options) but only set
252 bool fgInitFGRoot ( int argc, char **argv ) {
255 // First parse command line options looking for --fg-root=, this
256 // will override anything specified in a config file
257 root = fgScanForOption( "--fg-root=", argc, argv);
259 // Check in one of the user configuration files.
261 root = fgScanForOption( "--fg-root=" );
263 // Next check if fg-root is set as an env variable
264 if ( root.empty() ) {
265 char *envp = ::getenv( "FG_ROOT" );
266 if ( envp != NULL ) {
271 // Otherwise, default to a random compiled-in location if we can't
272 // find fg-root any other way.
273 if ( root.empty() ) {
274 #if defined( __CYGWIN__ )
275 root = "/FlightGear";
276 #elif defined( WIN32 )
277 root = "\\FlightGear";
278 #elif defined(OSX_BUNDLE)
279 /* the following code looks for the base package directly inside
280 the application bundle. This can be changed fairly easily by
281 fiddling with the code below. And yes, I know it's ugly and verbose.
283 CFBundleRef appBundle = CFBundleGetMainBundle();
284 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
285 CFRelease(appBundle);
287 // look for a 'data' subdir directly inside the bundle : is there
288 // a better place? maybe in Resources? I don't know ...
289 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
291 // now convert down to a path, and the a c-string
292 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
293 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
296 CFRelease(appBundle);
304 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
305 globals->set_fg_root(root);
311 // Read in configuration (files and command line options) but only set
313 bool fgInitFGAircraft ( int argc, char **argv ) {
316 // First parse command line options looking for --aircraft=, this
317 // will override anything specified in a config file
318 aircraft = fgScanForOption( "--aircraft=", argc, argv );
320 // Check in one of the user configuration files.
321 if ( aircraft.empty() )
322 aircraft = fgScanForOption( "--aircraft=" );
324 // if an aircraft was specified, set the property name
325 if ( !aircraft.empty() ) {
326 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
327 fgSetString("/sim/aircraft", aircraft.c_str() );
329 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
336 // Return the current base package version
337 string fgBasePackageVersion() {
338 SGPath base_path( globals->get_fg_root() );
339 base_path.append("version");
341 sg_gzifstream in( base_path.str() );
342 if ( !in.is_open() ) {
343 SGPath old_path( globals->get_fg_root() );
344 old_path.append( "Thanks" );
345 sg_gzifstream old( old_path.str() );
346 if ( !old.is_open() ) {
349 return "[old version]";
360 // Initialize the localization
361 SGPropertyNode *fgInitLocale(const char *language) {
362 SGPropertyNode *c_node = NULL, *d_node = NULL;
363 SGPropertyNode *intl = fgGetNode("/sim/intl");
365 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
367 // localization not defined
372 // Select the proper language from the list
374 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
375 for (unsigned int i = 0; i < locale.size(); i++) {
377 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
378 for (unsigned int j = 0; j < lang.size(); j++) {
380 if (!strcmp(lang[j]->getStringValue(), language)) {
389 d_node = intl->getChild("locale");
393 // Check for localized font
394 SGPropertyNode *font_n = c_node->getNode("font", true);
395 if ( !strcmp(font_n->getStringValue(), "") )
396 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
400 // Load the default strings
402 SGPath d_path( globals->get_fg_root() );
404 const char *d_path_str = d_node->getStringValue("strings");
406 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
410 d_path.append(d_path_str);
411 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
413 SGPropertyNode *strings = c_node->getNode("strings");
415 readProperties(d_path.str(), strings);
416 } catch (const sg_exception &e) {
417 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
422 // Load the language specific strings
424 if (c_node != d_node) {
425 SGPath c_path( globals->get_fg_root() );
427 const char *c_path_str = c_node->getStringValue("strings");
429 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
433 c_path.append(c_path_str);
434 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
437 readProperties(c_path.str(), strings);
438 } catch (const sg_exception &e) {
439 SG_LOG(SG_GENERAL, SG_ALERT,
440 "Unable to read the localized strings from " << c_path.str());
450 // Initialize the localization routines
451 bool fgDetectLanguage() {
452 char *language = ::getenv("LANG");
454 if (language == NULL) {
455 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
459 SGPropertyNode *locale = fgInitLocale(language);
461 SG_LOG(SG_GENERAL, SG_ALERT,
462 "No internationalization settings specified in preferences.xml" );
467 globals->set_locale( locale );
472 // Attempt to locate and parse the various non-XML config files in order
473 // from least precidence to greatest precidence
475 do_options (int argc, char ** argv)
477 // Check for $fg_root/system.fgfsrc
478 SGPath config( globals->get_fg_root() );
479 config.append( "system.fgfsrc" );
480 fgParseOptions(config.str());
482 #if defined( unix ) || defined( __CYGWIN__ )
483 config.concat( "." );
484 config.concat( hostname );
485 fgParseOptions(config.str());
488 // Check for ~/.fgfsrc
489 if ( homedir != NULL ) {
490 config.set( homedir );
491 config.append( ".fgfsrc" );
492 fgParseOptions(config.str());
495 #if defined( unix ) || defined( __CYGWIN__ )
496 // Check for ~/.fgfsrc.hostname
497 config.concat( "." );
498 config.concat( hostname );
499 fgParseOptions(config.str());
502 // Parse remaining command line options
503 // These will override anything specified in a config file
504 fgParseArgs(argc, argv);
508 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
509 SGPropertyNode *cache, int depth = 0 )
511 const int MAXDEPTH = 1;
514 ulDir *dirp = ulOpenDir(path.str().c_str());
516 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
521 while ((dire = ulReadDir(dirp)) != NULL) {
523 if (depth > MAXDEPTH)
526 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
527 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
531 next.append(dire->d_name);
533 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
534 if ( ! result.empty() )
538 int len = strlen(dire->d_name);
539 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
545 if (!cache->getChild("aircraft", i++, false))
548 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
550 n = entry->getNode("file", true);
551 n->setStringValue(dire->d_name);
552 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
554 n = entry->getNode("path", true);
555 n->setStringValue(path.str().c_str());
556 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
558 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
570 // Read in configuration (file and command line)
571 bool fgInitConfig ( int argc, char **argv ) {
573 // First, set some sane default values
576 // Read global preferences from $FG_ROOT/preferences.xml
577 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
578 fgLoadProps("preferences.xml", globals->get_props());
579 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
581 // Detect the required language as early as possible
582 if ( !fgDetectLanguage() ) {
586 SGPropertyNode autosave;
588 char *envp = ::getenv( "APPDATA" );
590 SGPath config( envp );
591 config.append( "flightgear.org" );
593 if ( homedir != NULL ) {
594 SGPath config( homedir );
595 config.append( ".fgfs" );
597 fgSetString("/sim/fg-home", config.c_str());
598 config.append( "autosave.xml" );
599 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
601 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
603 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
605 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
607 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
610 // Scan user config files and command line for a specified aircraft.
611 fgInitFGAircraft(argc, argv);
613 string aircraft = fgGetString( "/sim/aircraft", "" );
614 if ( aircraft.size() > 0 ) {
615 SGPath aircraft_search( globals->get_fg_root() );
616 aircraft_search.append( "Aircraft" );
618 string aircraft_set = aircraft + "-set.xml";
621 // check if the *-set.xml file is already in the cache
622 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
623 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
624 for (unsigned int i = 0; i < cache.size(); i++) {
625 const char *name = cache[i]->getStringValue("file", "");
626 if (aircraft_set == name) {
627 const char *path = cache[i]->getStringValue("path", "");
637 if (result.empty()) {
638 // prepare cache for rescan
639 SGPropertyNode *n = cache_root->getNode("fg-root", true);
640 n->setStringValue(globals->get_fg_root().c_str());
641 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
642 cache_root->removeChildren("aircraft");
644 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
647 if ( !result.empty() ) {
648 fgSetString( "/sim/aircraft-dir", result.c_str() );
649 SGPath full_name( result );
650 full_name.append( aircraft_set );
652 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
653 << " from " << full_name.str());
655 readProperties( full_name.str(), globals->get_props() );
656 } catch ( const sg_exception &e ) {
657 string message = "Error reading default aircraft: ";
658 message += e.getFormattedMessage();
659 SG_LOG(SG_INPUT, SG_ALERT, message);
663 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
669 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
672 copyProperties(&autosave, globals->get_props());
674 // parse options after loading aircraft to ensure any user
675 // overrides of defaults are honored.
676 do_options(argc, argv);
687 // This function is never used, but maybe useful in the future ???
690 // Preset lon/lat given an airport id
691 static bool fgSetPosFromAirportID( const string& id ) {
695 SG_LOG( SG_GENERAL, SG_INFO,
696 "Attempting to set starting position from airport code " << id );
698 if ( fgFindAirportID( id, &a ) ) {
700 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
701 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
703 // other code depends on the actual postition being set so set
705 fgSetDouble("/position/longitude-deg", a->longitude );
706 fgSetDouble("/position/latitude-deg", a->latitude );
708 SG_LOG( SG_GENERAL, SG_INFO,
709 "Position for " << id << " is (" << a->longitude
710 << ", " << a->latitude << ")" );
720 // Set current tower position lon/lat given an airport id
721 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
723 // tower height hard coded for now...
724 float towerheight=50.0f;
726 // make a little off the heading for 1 runway airports...
727 float fudge_lon = fabs(sin(hdg)) * .003f;
728 float fudge_lat = .003f - fudge_lon;
730 const FGAirport *a = fgFindAirportID( id);
732 fgSetDouble("/sim/tower/longitude-deg", a->getLongitude() + fudge_lon);
733 fgSetDouble("/sim/tower/latitude-deg", a->getLatitude() + fudge_lat);
734 fgSetDouble("/sim/tower/altitude-ft", a->getElevation() + towerheight);
742 struct FGTowerLocationListener : SGPropertyChangeListener {
743 void valueChanged(SGPropertyNode* node) {
744 const double hdg = fgGetDouble( "/orientation/heading-deg", 0);
745 const string id(node->getStringValue());
746 fgSetTowerPosFromAirportID(id, hdg);
750 void fgInitTowerLocationListener() {
751 fgGetNode("/sim/tower/airport-id", true)
752 ->addChangeListener( new FGTowerLocationListener(), true );
755 // Set current_options lon/lat given an airport id and heading (degrees)
756 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
760 // set initial position from runway and heading
762 SG_LOG( SG_GENERAL, SG_INFO,
763 "Attempting to set starting position from airport code "
764 << id << " heading " << tgt_hdg );
766 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
767 SG_LOG( SG_GENERAL, SG_ALERT,
768 "Failed to find a good runway for " << id << '\n' );
775 double lat2, lon2, az2;
776 double heading = r._heading;
777 double azimuth = heading + 180.0;
778 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
780 SG_LOG( SG_GENERAL, SG_INFO,
781 "runway = " << r._lon << ", " << r._lat
782 << " length = " << r._length * SG_FEET_TO_METER
783 << " heading = " << azimuth );
785 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
786 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
787 &lat2, &lon2, &az2 );
789 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
791 double odist = fgGetDouble("/sim/presets/offset-distance");
792 odist *= SG_NM_TO_METER;
793 double oaz = azimuth;
794 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
795 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
798 while ( oaz >= 360.0 ) { oaz -= 360.0; }
799 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
805 fgSetDouble("/sim/presets/longitude-deg", lon2 );
806 fgSetDouble("/sim/presets/latitude-deg", lat2 );
807 fgSetDouble("/sim/presets/heading-deg", heading );
809 // other code depends on the actual values being set ...
810 fgSetDouble("/position/longitude-deg", lon2 );
811 fgSetDouble("/position/latitude-deg", lat2 );
812 fgSetDouble("/orientation/heading-deg", heading );
814 SG_LOG( SG_GENERAL, SG_INFO,
815 "Position for " << id << " is ("
817 << lat2 << ") new heading is "
824 // Set current_options lon/lat given an airport id and runway number
825 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
829 // set initial position from airport and runway number
831 SG_LOG( SG_GENERAL, SG_INFO,
832 "Attempting to set starting position for "
833 << id << ":" << rwy );
835 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
836 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
837 "Failed to find runway " << rwy <<
838 " at airport " << id << ". Using default runway." );
845 double lat2, lon2, az2;
846 double heading = r._heading;
847 double azimuth = heading + 180.0;
848 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
850 SG_LOG( SG_GENERAL, SG_INFO,
851 "runway = " << r._lon << ", " << r._lat
852 << " length = " << r._length * SG_FEET_TO_METER
853 << " heading = " << azimuth );
855 geo_direct_wgs_84 ( 0, r._lat, r._lon,
857 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
858 &lat2, &lon2, &az2 );
860 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
863 double odist = fgGetDouble("/sim/presets/offset-distance");
864 odist *= SG_NM_TO_METER;
865 double oaz = azimuth;
866 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
868 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
869 heading = fgGetDouble("/sim/presets/heading-deg");
871 while ( oaz >= 360.0 ) { oaz -= 360.0; }
872 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
878 fgSetDouble("/sim/presets/longitude-deg", lon2 );
879 fgSetDouble("/sim/presets/latitude-deg", lat2 );
880 fgSetDouble("/sim/presets/heading-deg", heading );
882 // other code depends on the actual values being set ...
883 fgSetDouble("/position/longitude-deg", lon2 );
884 fgSetDouble("/position/latitude-deg", lat2 );
885 fgSetDouble("/orientation/heading-deg", heading );
887 SG_LOG( SG_GENERAL, SG_INFO,
888 "Position for " << id << " is ("
890 << lat2 << ") new heading is "
897 static void fgSetDistOrAltFromGlideSlope() {
898 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
899 string apt_id = fgGetString("/sim/presets/airport-id");
900 double gs = fgGetDouble("/sim/presets/glideslope-deg")
901 * SG_DEGREES_TO_RADIANS ;
902 double od = fgGetDouble("/sim/presets/offset-distance");
903 double alt = fgGetDouble("/sim/presets/altitude-ft");
905 double apt_elev = 0.0;
906 if ( ! apt_id.empty() ) {
907 apt_elev = fgGetAirportElev( apt_id );
908 if ( apt_elev < -9990.0 ) {
915 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
916 // set altitude from glideslope and offset-distance
917 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
918 alt = fabs(od*tan(gs)) + apt_elev;
919 fgSetDouble("/sim/presets/altitude-ft", alt);
920 fgSetBool("/sim/presets/onground", false);
921 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
923 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
924 // set offset-distance from glideslope and altitude
925 od = (alt - apt_elev) / tan(gs);
926 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
927 fgSetDouble("/sim/presets/offset-distance", od);
928 fgSetBool("/sim/presets/onground", false);
929 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
931 } else if( fabs(gs) > 0.01 ) {
932 SG_LOG( SG_GENERAL, SG_ALERT,
933 "Glideslope given but not altitude or offset-distance." );
934 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
935 fgSetDouble("/sim/presets/glideslope-deg", 0);
936 fgSetBool("/sim/presets/onground", true);
941 // Set current_options lon/lat given an airport id and heading (degrees)
942 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
944 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
946 // set initial position from runway and heading
948 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
949 << id << ":" << freq );
951 double lon = nav->get_lon();
952 double lat = nav->get_lat();
954 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
956 double odist = fgGetDouble("/sim/presets/offset-distance")
958 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
960 while ( oaz >= 360.0 ) { oaz -= 360.0; }
961 double olat, olon, az2;
962 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
969 fgSetDouble("/sim/presets/longitude-deg", lon );
970 fgSetDouble("/sim/presets/latitude-deg", lat );
972 // other code depends on the actual values being set ...
973 fgSetDouble("/position/longitude-deg", lon );
974 fgSetDouble("/position/latitude-deg", lat );
975 fgSetDouble("/orientation/heading-deg",
976 fgGetDouble("/sim/presets/heading-deg") );
978 SG_LOG( SG_GENERAL, SG_INFO,
979 "Position for " << id << ":" << freq << " is ("
980 << lon << ", "<< lat << ")" );
984 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
985 << id << ":" << freq );
990 // Set current_options lon/lat given an aircraft carrier id
991 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
993 // set initial position from runway and heading
997 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
998 double lon = geodPos.getLongitudeDeg();
999 double lat = geodPos.getLatitudeDeg();
1000 double alt = geodPos.getElevationFt();
1002 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1003 << carrier << " at lat = " << lat << ", lon = " << lon
1004 << ", alt = " << alt << ", heading = " << heading);
1006 fgSetDouble("/sim/presets/longitude-deg", lon);
1007 fgSetDouble("/sim/presets/latitude-deg", lat);
1008 fgSetDouble("/sim/presets/altitude-ft", alt);
1009 fgSetDouble("/sim/presets/heading-deg", heading);
1010 fgSetDouble("/position/longitude-deg", lon);
1011 fgSetDouble("/position/latitude-deg", lat);
1012 fgSetDouble("/position/altitude-ft", alt);
1013 fgSetDouble("/orientation/heading-deg", heading);
1015 fgSetString("/sim/presets/speed-set", "UVW");
1016 fgSetDouble("/velocities/uBody-fps", uvw(0));
1017 fgSetDouble("/velocities/vBody-fps", uvw(1));
1018 fgSetDouble("/velocities/wBody-fps", uvw(2));
1019 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1020 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1021 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1023 fgSetBool("/sim/presets/onground", true);
1027 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1033 // Set current_options lon/lat given an airport id and heading (degrees)
1034 static bool fgSetPosFromFix( const string& id ) {
1037 // set initial position from runway and heading
1038 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1039 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1042 double lon = fix.get_lon();
1043 double lat = fix.get_lat();
1045 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1047 double odist = fgGetDouble("/sim/presets/offset-distance")
1049 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1051 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1052 double olat, olon, az2;
1053 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1060 fgSetDouble("/sim/presets/longitude-deg", lon );
1061 fgSetDouble("/sim/presets/latitude-deg", lat );
1063 // other code depends on the actual values being set ...
1064 fgSetDouble("/position/longitude-deg", lon );
1065 fgSetDouble("/position/latitude-deg", lat );
1066 fgSetDouble("/orientation/heading-deg",
1067 fgGetDouble("/sim/presets/heading-deg") );
1069 SG_LOG( SG_GENERAL, SG_INFO,
1070 "Position for " << id << " is ("
1071 << lon << ", "<< lat << ")" );
1075 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1083 * Initialize vor/ndb/ils/fix list management and query systems (as
1084 * well as simple airport db list)
1089 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1091 SGPath aptdb( globals->get_fg_root() );
1092 aptdb.append( "Airports/apt.dat" );
1094 SGPath p_metar( globals->get_fg_root() );
1095 p_metar.append( "Airports/metar.dat" );
1097 FGAirportList *airports = new FGAirportList();
1098 globals->set_airports( airports );
1099 FGRunwayList *runways = new FGRunwayList();
1100 globals->set_runways( runways );
1102 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1104 FGNavList *navlist = new FGNavList;
1105 FGNavList *loclist = new FGNavList;
1106 FGNavList *gslist = new FGNavList;
1107 FGNavList *dmelist = new FGNavList;
1108 FGNavList *mkrlist = new FGNavList;
1109 FGNavList *tacanlist = new FGNavList;
1110 FGNavList *carrierlist = new FGNavList;
1111 FGTACANList *channellist = new FGTACANList;
1113 globals->set_navlist( navlist );
1114 globals->set_loclist( loclist );
1115 globals->set_gslist( gslist );
1116 globals->set_dmelist( dmelist );
1117 globals->set_mkrlist( mkrlist );
1118 globals->set_tacanlist( tacanlist );
1119 globals->set_carrierlist( carrierlist );
1120 globals->set_channellist( channellist );
1122 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1123 SG_LOG( SG_GENERAL, SG_ALERT,
1124 "Problems loading one or more navigational database" );
1127 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1128 // align all the localizers with their corresponding runways
1129 // since data sources are good for cockpit navigation
1130 // purposes, but not always to the error tolerances needed to
1131 // exactly place these items.
1133 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1135 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1138 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1139 SGPath p_fix( globals->get_fg_root() );
1140 p_fix.append( "Navaids/fix.dat" );
1141 FGFixList *fixlist = new FGFixList;
1142 fixlist->init( p_fix );
1143 globals->set_fixlist( fixlist );
1145 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1146 SGPath p_awy( globals->get_fg_root() );
1147 p_awy.append( "Navaids/awy.dat" );
1148 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1149 //cerr << "Loading Airways" << endl;
1150 awyNet->load (p_awy );
1152 //cerr << "initializing airways" << endl;
1153 globals->set_airwaynet( awyNet );
1159 // Set the initial position based on presets (or defaults)
1160 bool fgInitPosition() {
1161 // cout << "fgInitPosition()" << endl;
1162 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1163 * SG_DEGREES_TO_RADIANS ;
1164 double od = fgGetDouble("/sim/presets/offset-distance");
1165 double alt = fgGetDouble("/sim/presets/altitude-ft");
1167 bool set_pos = false;
1169 // If glideslope is specified, then calculate offset-distance or
1170 // altitude relative to glide slope if either of those was not
1172 if ( fabs( gs ) > 0.01 ) {
1173 fgSetDistOrAltFromGlideSlope();
1177 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1178 // If not, check for an airport-id and use that.
1179 // If not, default to the middle of the KSFO field.
1180 // The default values for lon/lat are deliberately out of range
1181 // so that the airport-id can take effect; valid lon/lat will
1182 // override airport-id, however.
1183 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1184 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1185 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1186 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1191 string apt = fgGetString("/sim/presets/airport-id");
1192 string rwy_no = fgGetString("/sim/presets/runway");
1193 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1194 double hdg = fgGetDouble("/sim/presets/heading-deg");
1195 string vor = fgGetString("/sim/presets/vor-id");
1196 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1197 string ndb = fgGetString("/sim/presets/ndb-id");
1198 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1199 string carrier = fgGetString("/sim/presets/carrier");
1200 string parkpos = fgGetString("/sim/presets/parkpos");
1201 string fix = fgGetString("/sim/presets/fix");
1203 fgSetDouble( "/orientation/heading-deg", hdg );
1205 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1206 // An airport + runway is requested
1207 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1208 // set tower position (a little off the heading for single
1210 fgSetString("/sim/tower/airport-id", apt.c_str());
1215 if ( !set_pos && !apt.empty() ) {
1216 // An airport is requested (find runway closest to hdg)
1217 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1218 // set tower position (a little off the heading for single
1220 fgSetString("/sim/tower/airport-id", apt.c_str());
1225 if ( !set_pos && !vor.empty() ) {
1226 // a VOR is requested
1227 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1232 if ( !set_pos && !ndb.empty() ) {
1233 // an NDB is requested
1234 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1239 if ( !set_pos && !carrier.empty() ) {
1240 // an aircraft carrier is requested
1241 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1246 if ( !set_pos && !fix.empty() ) {
1247 // a Fix is requested
1248 if ( fgSetPosFromFix( fix ) ) {
1254 // No lon/lat specified, no airport specified, default to
1255 // middle of KSFO field.
1256 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1257 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1260 fgSetDouble( "/position/longitude-deg",
1261 fgGetDouble("/sim/presets/longitude-deg") );
1262 fgSetDouble( "/position/latitude-deg",
1263 fgGetDouble("/sim/presets/latitude-deg") );
1265 // determine if this should be an on-ground or in-air start
1266 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1267 fgSetBool("/sim/presets/onground", false);
1269 fgSetBool("/sim/presets/onground", true);
1276 // General house keeping initializations
1277 bool fgInitGeneral() {
1280 #if defined(FX) && defined(XMESA)
1281 char *mesa_win_state;
1284 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1285 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1287 root = globals->get_fg_root();
1288 if ( ! root.length() ) {
1289 // No root path set? Then bail ...
1290 SG_LOG( SG_GENERAL, SG_ALERT,
1291 "Cannot continue without a path to the base package "
1292 << "being defined." );
1295 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1297 #if defined(FX) && defined(XMESA)
1298 // initialize full screen flag
1299 globals->set_fullscreen(false);
1300 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1301 // Test for the MESA_GLX_FX env variable
1302 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1303 // test if we are fullscreen mesa/glide
1304 if ( (mesa_win_state[0] == 'f') ||
1305 (mesa_win_state[0] == 'F') ) {
1306 globals->set_fullscreen(true);
1316 // Initialize the flight model subsystem. This just creates the
1317 // object. The actual fdm initialization is delayed until we get a
1318 // proper scenery elevation hit. This is checked for in main.cxx
1322 if ( cur_fdm_state ) {
1323 delete cur_fdm_state;
1327 double dt = 1.0 / fgGetInt("/sim/model-hz");
1328 string model = fgGetString("/sim/flight-model");
1331 if ( model == "larcsim" ) {
1332 cur_fdm_state = new FGLaRCsim( dt );
1333 } else if ( model == "jsb" ) {
1334 cur_fdm_state = new FGJSBsim( dt );
1336 } else if ( model == "ada" ) {
1337 cur_fdm_state = new FGADA( dt );
1338 } else if ( model == "acms" ) {
1339 cur_fdm_state = new FGACMS( dt );
1341 } else if ( model == "balloon" ) {
1342 cur_fdm_state = new FGBalloonSim( dt );
1343 } else if ( model == "magic" ) {
1344 cur_fdm_state = new FGMagicCarpet( dt );
1345 } else if ( model == "ufo" ) {
1346 cur_fdm_state = new FGUFO( dt );
1347 } else if ( model == "external" ) {
1348 // external is a synonym for "--fdm=null" and is
1349 // maintained here for backwards compatibility
1350 cur_fdm_state = new FGNullFDM( dt );
1351 } else if ( model.find("network") == 0 ) {
1352 string host = "localhost";
1356 string net_options = model.substr(8);
1357 string::size_type begin, end;
1360 end = net_options.find( ",", begin );
1361 if ( end != string::npos ) {
1362 host = net_options.substr(begin, end - begin);
1366 end = net_options.find( ",", begin );
1367 if ( end != string::npos ) {
1368 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1372 end = net_options.find( ",", begin );
1373 if ( end != string::npos ) {
1374 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1378 end = net_options.find( ",", begin );
1379 if ( end != string::npos ) {
1380 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1383 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1384 } else if ( model.find("pipe") == 0 ) {
1385 // /* old */ string pipe_path = model.substr(5);
1386 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1387 string pipe_path = "";
1388 string pipe_protocol = "";
1389 string pipe_options = model.substr(5);
1390 string::size_type begin, end;
1393 end = pipe_options.find( ",", begin );
1394 if ( end != string::npos ) {
1395 pipe_path = pipe_options.substr(begin, end - begin);
1398 // protocol (last option)
1399 pipe_protocol = pipe_options.substr(begin);
1400 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1401 } else if ( model == "null" ) {
1402 cur_fdm_state = new FGNullFDM( dt );
1403 } else if ( model == "yasim" ) {
1404 cur_fdm_state = new YASim( dt );
1406 SG_LOG(SG_GENERAL, SG_ALERT,
1407 "Unrecognized flight model '" << model
1408 << "', cannot init flight dynamics model.");
1412 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1417 // Initialize view parameters
1419 // force update of model so that viewer can get some data...
1420 globals->get_aircraft_model()->update(0);
1421 // run update for current view so that data is current...
1422 globals->get_viewmgr()->update(0);
1426 SGTime *fgInitTime() {
1428 static const SGPropertyNode *longitude
1429 = fgGetNode("/position/longitude-deg");
1430 static const SGPropertyNode *latitude
1431 = fgGetNode("/position/latitude-deg");
1432 static const SGPropertyNode *cur_time_override
1433 = fgGetNode("/sim/time/cur-time-override", true);
1435 SGPath zone( globals->get_fg_root() );
1436 zone.append( "Timezone" );
1437 SGTime *t = new SGTime( longitude->getDoubleValue()
1438 * SGD_DEGREES_TO_RADIANS,
1439 latitude->getDoubleValue()
1440 * SGD_DEGREES_TO_RADIANS,
1442 cur_time_override->getLongValue() );
1444 globals->set_warp_delta( 0 );
1446 t->update( 0.0, 0.0,
1447 cur_time_override->getLongValue(),
1448 globals->get_warp() );
1454 // set up a time offset (aka warp) if one is specified
1455 void fgInitTimeOffset() {
1456 static const SGPropertyNode *longitude
1457 = fgGetNode("/position/longitude-deg");
1458 static const SGPropertyNode *latitude
1459 = fgGetNode("/position/latitude-deg");
1460 static const SGPropertyNode *cur_time_override
1461 = fgGetNode("/sim/time/cur-time-override", true);
1463 // Handle potential user specified time offsets
1464 int orig_warp = globals->get_warp();
1465 SGTime *t = globals->get_time_params();
1466 time_t cur_time = t->get_cur_time();
1467 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1468 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1469 time_t aircraftLocalTime =
1470 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1472 // Okay, we now have several possible scenarios
1473 int offset = fgGetInt("/sim/startup/time-offset");
1474 string offset_type = fgGetString("/sim/startup/time-offset-type");
1477 if ( offset_type == "real" ) {
1479 } else if ( offset_type == "dawn" ) {
1480 warp = fgTimeSecondsUntilSunAngle( cur_time,
1481 longitude->getDoubleValue()
1482 * SGD_DEGREES_TO_RADIANS,
1483 latitude->getDoubleValue()
1484 * SGD_DEGREES_TO_RADIANS,
1486 } else if ( offset_type == "morning" ) {
1487 warp = fgTimeSecondsUntilSunAngle( cur_time,
1488 longitude->getDoubleValue()
1489 * SGD_DEGREES_TO_RADIANS,
1490 latitude->getDoubleValue()
1491 * SGD_DEGREES_TO_RADIANS,
1493 } else if ( offset_type == "noon" ) {
1494 warp = fgTimeSecondsUntilSunAngle( cur_time,
1495 longitude->getDoubleValue()
1496 * SGD_DEGREES_TO_RADIANS,
1497 latitude->getDoubleValue()
1498 * SGD_DEGREES_TO_RADIANS,
1500 } else if ( offset_type == "afternoon" ) {
1501 warp = fgTimeSecondsUntilSunAngle( cur_time,
1502 longitude->getDoubleValue()
1503 * SGD_DEGREES_TO_RADIANS,
1504 latitude->getDoubleValue()
1505 * SGD_DEGREES_TO_RADIANS,
1507 } else if ( offset_type == "dusk" ) {
1508 warp = fgTimeSecondsUntilSunAngle( cur_time,
1509 longitude->getDoubleValue()
1510 * SGD_DEGREES_TO_RADIANS,
1511 latitude->getDoubleValue()
1512 * SGD_DEGREES_TO_RADIANS,
1514 } else if ( offset_type == "evening" ) {
1515 warp = fgTimeSecondsUntilSunAngle( cur_time,
1516 longitude->getDoubleValue()
1517 * SGD_DEGREES_TO_RADIANS,
1518 latitude->getDoubleValue()
1519 * SGD_DEGREES_TO_RADIANS,
1521 } else if ( offset_type == "midnight" ) {
1522 warp = fgTimeSecondsUntilSunAngle( cur_time,
1523 longitude->getDoubleValue()
1524 * SGD_DEGREES_TO_RADIANS,
1525 latitude->getDoubleValue()
1526 * SGD_DEGREES_TO_RADIANS,
1528 } else if ( offset_type == "system-offset" ) {
1531 } else if ( offset_type == "gmt-offset" ) {
1532 warp = offset - (currGMT - systemLocalTime);
1534 } else if ( offset_type == "latitude-offset" ) {
1535 warp = offset - (aircraftLocalTime - systemLocalTime);
1537 } else if ( offset_type == "system" ) {
1538 warp = offset - (systemLocalTime - currGMT) - cur_time;
1539 } else if ( offset_type == "gmt" ) {
1540 warp = offset - cur_time;
1541 } else if ( offset_type == "latitude" ) {
1542 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1544 SG_LOG( SG_GENERAL, SG_ALERT,
1545 "FG_TIME::Unsupported offset type " << offset_type );
1548 globals->set_warp( orig_warp + warp );
1549 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1550 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1551 cur_time_override->getLongValue(),
1552 globals->get_warp() );
1554 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1555 << globals->get_warp() );
1559 // This is the top level init routine which calls all the other
1560 // initialization routines. If you are adding a subsystem to flight
1561 // gear, its initialization call should located in this routine.
1562 // Returns non-zero if a problem encountered.
1563 bool fgInitSubsystems() {
1564 // static const SGPropertyNode *longitude
1565 // = fgGetNode("/sim/presets/longitude-deg");
1566 // static const SGPropertyNode *latitude
1567 // = fgGetNode("/sim/presets/latitude-deg");
1568 // static const SGPropertyNode *altitude
1569 // = fgGetNode("/sim/presets/altitude-ft");
1570 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1571 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1573 ////////////////////////////////////////////////////////////////////
1574 // Initialize the event manager subsystem.
1575 ////////////////////////////////////////////////////////////////////
1577 globals->get_event_mgr()->init();
1578 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1580 ////////////////////////////////////////////////////////////////////
1581 // Initialize the property interpolator subsystem. Put into the INIT
1582 // group because the "nasal" subsystem may need it at GENERAL take-down.
1583 ////////////////////////////////////////////////////////////////////
1584 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1587 ////////////////////////////////////////////////////////////////////
1588 // Add the FlightGear property utilities.
1589 ////////////////////////////////////////////////////////////////////
1590 globals->add_subsystem("properties", new FGProperties);
1592 ////////////////////////////////////////////////////////////////////
1593 // Initialize the material property subsystem.
1594 ////////////////////////////////////////////////////////////////////
1596 SGPath mpath( globals->get_fg_root() );
1597 mpath.append( "materials.xml" );
1598 string season = fgGetString("/sim/startup/season", "summer");
1599 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str()) ) {
1600 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1605 ////////////////////////////////////////////////////////////////////
1606 // Initialize the scenery management subsystem.
1607 ////////////////////////////////////////////////////////////////////
1609 if ( globals->get_tile_mgr()->init() ) {
1610 // Load the local scenery data
1611 double visibility_meters = fgGetDouble("/environment/visibility-m");
1613 globals->get_tile_mgr()->update( visibility_meters );
1615 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1619 // cause refresh of viewer scenery timestamps every 15 seconds...
1620 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1621 globals->get_tile_mgr(),
1622 &FGTileMgr::refresh_view_timestamps,
1626 ////////////////////////////////////////////////////////////////////
1627 // Initialize the flight model subsystem.
1628 ////////////////////////////////////////////////////////////////////
1632 // allocates structures so must happen before any of the flight
1633 // model or control parameters are set
1634 fgAircraftInit(); // In the future this might not be the case.
1636 ////////////////////////////////////////////////////////////////////
1637 // Initialize the aircraft systems and instrumentation (before the
1639 ////////////////////////////////////////////////////////////////////
1641 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1642 globals->add_subsystem("systems", new FGSystemMgr);
1644 ////////////////////////////////////////////////////////////////////
1645 // Initialize the XML Autopilot subsystem.
1646 ////////////////////////////////////////////////////////////////////
1648 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1649 globals->add_subsystem( "route-manager", new FGRouteMgr );
1652 ////////////////////////////////////////////////////////////////////
1653 // Initialize the view manager subsystem.
1654 ////////////////////////////////////////////////////////////////////
1658 ////////////////////////////////////////////////////////////////////
1659 // Create and register the logger.
1660 ////////////////////////////////////////////////////////////////////
1662 globals->add_subsystem("logger", new FGLogger);
1664 ////////////////////////////////////////////////////////////////////
1665 // Create and register the XML GUI.
1666 ////////////////////////////////////////////////////////////////////
1668 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1671 ////////////////////////////////////////////////////////////////////
1672 // Initialize the local time subsystem.
1673 ////////////////////////////////////////////////////////////////////
1675 // update the current timezone each 30 minutes
1676 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1677 &fgUpdateLocalTime, 30*60 );
1678 fgInitTimeOffset(); // the environment subsystem needs this
1681 ////////////////////////////////////////////////////////////////////
1682 // Initialize the weather subsystem.
1683 ////////////////////////////////////////////////////////////////////
1685 // Initialize the weather modeling subsystem
1686 globals->add_subsystem("environment", new FGEnvironmentMgr);
1689 ////////////////////////////////////////////////////////////////////
1690 // Initialize the lighting subsystem.
1691 ////////////////////////////////////////////////////////////////////
1693 globals->add_subsystem("lighting", new FGLight);
1695 //////////////////////////////////////////////////////////////////////
1696 // Initialize the 2D cloud subsystem.
1697 ////////////////////////////////////////////////////////////////////
1698 fgGetBool("/sim/rendering/bump-mapping", false);
1700 #ifdef ENABLE_AUDIO_SUPPORT
1701 ////////////////////////////////////////////////////////////////////
1702 // Initialize the sound subsystem.
1703 ////////////////////////////////////////////////////////////////////
1705 init_volume = fgGetFloat("/sim/sound/volume");
1706 fgSetFloat("/sim/sound/volume", 0.0f);
1707 globals->set_soundmgr(new SGSoundMgr);
1708 globals->get_soundmgr()->init();
1709 globals->get_soundmgr()->bind();
1712 ////////////////////////////////////////////////////////////////////
1713 // Initialize the sound-effects subsystem.
1714 ////////////////////////////////////////////////////////////////////
1716 globals->add_subsystem("fx", new FGFX);
1717 globals->add_subsystem("voice", new FGVoiceMgr);
1720 ////////////////////////////////////////////////////////////////////
1721 // Initialise the ATC Manager
1722 ////////////////////////////////////////////////////////////////////
1724 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1725 globals->set_ATC_mgr(new FGATCMgr);
1726 globals->get_ATC_mgr()->init();
1728 ////////////////////////////////////////////////////////////////////
1729 // Initialise the AI Manager
1730 ////////////////////////////////////////////////////////////////////
1732 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1733 globals->set_AI_mgr(new FGAIMgr);
1734 globals->get_AI_mgr()->init();
1736 ////////////////////////////////////////////////////////////////////
1737 // Initialise the AI Model Manager
1738 ////////////////////////////////////////////////////////////////////
1739 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1740 globals->add_subsystem("ai_model", new FGAIManager);
1741 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1744 // It's probably a good idea to initialize the top level traffic manager
1745 // After the AI and ATC systems have been initialized properly.
1746 // AI Traffic manager
1747 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1750 ////////////////////////////////////////////////////////////////////
1751 // Initialize the cockpit subsystem
1752 ////////////////////////////////////////////////////////////////////
1753 if( fgCockpitInit( ¤t_aircraft )) {
1754 // Cockpit initialized ok.
1756 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1761 ////////////////////////////////////////////////////////////////////
1762 // Initialize I/O subsystem.
1763 ////////////////////////////////////////////////////////////////////
1765 globals->get_io()->init();
1766 globals->get_io()->bind();
1769 ////////////////////////////////////////////////////////////////////
1770 // Add a new 2D panel.
1771 ////////////////////////////////////////////////////////////////////
1773 string panel_path = fgGetString("/sim/panel/path",
1774 "Panels/Default/default.xml");
1776 globals->set_current_panel( fgReadPanel(panel_path) );
1777 if (globals->get_current_panel() == 0) {
1778 SG_LOG( SG_INPUT, SG_ALERT,
1779 "Error reading new panel from " << panel_path );
1781 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1782 globals->get_current_panel()->init();
1783 globals->get_current_panel()->bind();
1787 ////////////////////////////////////////////////////////////////////
1788 // Initialize the controls subsystem.
1789 ////////////////////////////////////////////////////////////////////
1791 globals->get_controls()->init();
1792 globals->get_controls()->bind();
1795 ////////////////////////////////////////////////////////////////////
1796 // Initialize the input subsystem.
1797 ////////////////////////////////////////////////////////////////////
1799 globals->add_subsystem("input", new FGInput);
1802 ////////////////////////////////////////////////////////////////////
1803 // Initialize the replay subsystem
1804 ////////////////////////////////////////////////////////////////////
1805 globals->add_subsystem("replay", new FGReplay);
1807 ////////////////////////////////////////////////////////////////////
1808 // Bind and initialize subsystems.
1809 ////////////////////////////////////////////////////////////////////
1811 globals->get_subsystem_mgr()->bind();
1812 globals->get_subsystem_mgr()->init();
1814 ////////////////////////////////////////////////////////////////////
1815 // Initialize multiplayer subsystem
1816 ////////////////////////////////////////////////////////////////////
1818 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1819 globals->get_multiplayer_mgr()->init();
1821 ////////////////////////////////////////////////////////////////////////
1822 // Initialize the Nasal interpreter.
1823 // Do this last, so that the loaded scripts see initialized state
1824 ////////////////////////////////////////////////////////////////////////
1825 FGNasalSys* nasal = new FGNasalSys();
1826 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1829 // initialize methods that depend on other subsystems.
1830 globals->get_subsystem_mgr()->postinit();
1832 ////////////////////////////////////////////////////////////////////////
1833 // End of subsystem initialization.
1834 ////////////////////////////////////////////////////////////////////
1836 SG_LOG( SG_GENERAL, SG_INFO, endl);
1838 // Save the initial state for future
1840 globals->saveInitialState();
1846 void fgReInitSubsystems()
1848 // static const SGPropertyNode *longitude
1849 // = fgGetNode("/sim/presets/longitude-deg");
1850 // static const SGPropertyNode *latitude
1851 // = fgGetNode("/sim/presets/latitude-deg");
1852 static const SGPropertyNode *altitude
1853 = fgGetNode("/sim/presets/altitude-ft");
1854 static const SGPropertyNode *master_freeze
1855 = fgGetNode("/sim/freeze/master");
1857 SG_LOG( SG_GENERAL, SG_INFO,
1858 "fgReInitSubsystems(): /position/altitude = "
1859 << altitude->getDoubleValue() );
1861 bool freeze = master_freeze->getBoolValue();
1863 fgSetBool("/sim/freeze/master", true);
1865 fgSetBool("/sim/crashed", false);
1867 // Force reupdating the positions of the ai 3d models. They are used for
1868 // initializing ground level for the FDM.
1869 globals->get_subsystem("ai_model")->reinit();
1871 // Initialize the FDM
1874 // allocates structures so must happen before any of the flight
1875 // model or control parameters are set
1876 fgAircraftInit(); // In the future this might not be the case.
1878 // reload offsets from config defaults
1879 globals->get_viewmgr()->reinit();
1883 globals->get_controls()->reset_all();
1885 fgUpdateLocalTime();
1887 // re-init to proper time of day setting
1891 fgSetBool("/sim/freeze/master", false);
1893 fgSetBool("/sim/sceneryloaded",false);