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., 675 Mass Ave, Cambridge, MA 02139, USA.
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef SG_MATH_EXCEPTION_CLASH
36 #include <string.h> // strcmp()
38 #if defined( unix ) || defined( __CYGWIN__ )
39 # include <unistd.h> // for gethostname()
42 // work around a stdc++ lib bug in some versions of linux, but doesn't
43 // seem to hurt to have this here for all versions of Linux.
45 # define _G_NO_EXTERN_TEMPLATES
48 #include <simgear/compiler.h>
52 #include <simgear/constants.h>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/structure/exception.hxx>
55 #include <simgear/structure/event_mgr.hxx>
56 #include <simgear/math/point3d.hxx>
57 #include <simgear/math/polar3d.hxx>
58 #include <simgear/math/sg_geodesy.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/interpolator.hxx>
61 #include <simgear/scene/material/matlib.hxx>
62 #include <simgear/timing/sg_time.hxx>
63 #include <simgear/timing/lowleveltime.h>
65 #include <Aircraft/aircraft.hxx>
66 #include <Aircraft/replay.hxx>
67 #include <Airports/apt_loader.hxx>
68 #include <Airports/runways.hxx>
69 #include <Airports/simple.hxx>
70 #include <AIModel/AIManager.hxx>
71 #include <ATC/ATCdisplay.hxx>
72 #include <ATC/ATCmgr.hxx>
73 #include <ATC/AIMgr.hxx>
74 #include <Autopilot/auto_gui.hxx>
75 #include <Autopilot/route_mgr.hxx>
76 #include <Autopilot/xmlauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/panel.hxx>
79 #include <Cockpit/panel_io.hxx>
81 #include <FDM/SP/ADA.hxx>
82 #include <FDM/SP/ACMS.hxx>
84 #include <FDM/Balloon.h>
85 #include <FDM/ExternalNet/ExternalNet.hxx>
86 #include <FDM/ExternalPipe/ExternalPipe.hxx>
87 #include <FDM/JSBSim/JSBSim.hxx>
88 #include <FDM/LaRCsim/LaRCsim.hxx>
89 #include <FDM/MagicCarpet.hxx>
90 #include <FDM/UFO.hxx>
91 #include <FDM/NullFDM.hxx>
92 #include <FDM/YASim/YASim.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Include/general.hxx>
95 #include <Input/input.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Model/acmodel.hxx>
98 #include <AIModel/submodel.hxx>
99 #include <AIModel/AIManager.hxx>
100 #include <Navaids/navdb.hxx>
101 #include <Navaids/navlist.hxx>
102 #include <Scenery/scenery.hxx>
103 #include <Scenery/tilemgr.hxx>
104 #include <Scripting/NasalSys.hxx>
105 #include <Sound/fg_fx.hxx>
106 #include <Sound/beacon.hxx>
107 #include <Sound/morse.hxx>
108 #include <Systems/system_mgr.hxx>
109 #include <Time/light.hxx>
110 #include <Time/sunsolver.hxx>
111 #include <Time/tmp.hxx>
112 #include <Traffic/TrafficMgr.hxx>
115 #include <MultiPlayer/multiplaymgr.hxx>
118 #include <Environment/environment_mgr.hxx>
120 #include "fg_init.hxx"
122 #include "fg_commands.hxx"
123 #include "fg_props.hxx"
124 #include "options.hxx"
125 #include "globals.hxx"
126 #include "logger.hxx"
127 #include "viewmgr.hxx"
130 #if defined(FX) && defined(XMESA)
131 #include <GL/xmesa.h>
134 SG_USING_STD(string);
138 extern const char *default_root;
142 // Scan the command line options for the specified option and return
144 static string fgScanForOption( const string& option, int argc, char **argv ) {
147 if (hostname == NULL)
150 gethostname(_hostname, 256);
151 hostname = strdup(_hostname);
152 free_hostname = true;
155 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
157 int len = option.length();
160 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
162 string arg = argv[i];
163 if ( arg.find( option ) == 0 ) {
164 return arg.substr( len );
174 // Scan the user config files for the specified option and return
176 static string fgScanForOption( const string& option, const string& path ) {
177 sg_gzifstream in( path );
178 if ( !in.is_open() ) {
182 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
184 int len = option.length();
188 while ( ! in.eof() ) {
191 while ( in.get(c) && c != '\0' ) {
196 #if defined( macintosh )
197 getline( in, line, '\r' );
199 getline( in, line, '\n' );
202 // catch extraneous (DOS) line ending character
203 if ( line[line.length() - 1] < 32 ) {
204 line = line.substr( 0, line.length()-1 );
207 if ( line.find( option ) == 0 ) {
208 return line.substr( len );
217 // Scan the user config files for the specified option and return
219 static string fgScanForOption( const string& option ) {
222 #if defined( unix ) || defined( __CYGWIN__ )
223 // Next check home directory for .fgfsrc.hostname file
225 if ( homedir != NULL ) {
226 SGPath config( homedir );
227 config.append( ".fgfsrc" );
228 config.concat( "." );
229 config.concat( hostname );
230 arg = fgScanForOption( option, config.str() );
235 // Next check home directory for .fgfsrc file
237 if ( homedir != NULL ) {
238 SGPath config( homedir );
239 config.append( ".fgfsrc" );
240 arg = fgScanForOption( option, config.str() );
245 // Check for $fg_root/system.fgfsrc
246 SGPath config( globals->get_fg_root() );
247 config.append( "system.fgfsrc" );
248 arg = fgScanForOption( option, config.str() );
255 // Read in configuration (files and command line options) but only set
257 bool fgInitFGRoot ( int argc, char **argv ) {
260 // First parse command line options looking for --fg-root=, this
261 // will override anything specified in a config file
262 root = fgScanForOption( "--fg-root=", argc, argv);
264 // Check in one of the user configuration files.
266 root = fgScanForOption( "--fg-root=" );
268 // Next check if fg-root is set as an env variable
269 if ( root.empty() ) {
270 char *envp = ::getenv( "FG_ROOT" );
271 if ( envp != NULL ) {
276 // Otherwise, default to a random compiled-in location if we can't
277 // find fg-root any other way.
278 if ( root.empty() ) {
279 #if defined( __CYGWIN__ )
280 root = "/FlightGear";
281 #elif defined( WIN32 )
282 root = "\\FlightGear";
283 #elif defined(OSX_BUNDLE)
284 /* the following code looks for the base package directly inside
285 the application bundle. This can be changed fairly easily by
286 fiddling with the code below. And yes, I know it's ugly and verbose.
288 CFBundleRef appBundle = CFBundleGetMainBundle();
289 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
290 CFRelease(appBundle);
292 // look for a 'data' subdir directly inside the bundle : is there
293 // a better place? maybe in Resources? I don't know ...
294 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
296 // now convert down to a path, and the a c-string
297 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
298 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
301 CFRelease(appBundle);
309 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
310 globals->set_fg_root(root);
316 // Read in configuration (files and command line options) but only set
318 bool fgInitFGAircraft ( int argc, char **argv ) {
321 // First parse command line options looking for --aircraft=, this
322 // will override anything specified in a config file
323 aircraft = fgScanForOption( "--aircraft=", argc, argv );
325 // Check in one of the user configuration files.
326 if ( aircraft.empty() )
327 aircraft = fgScanForOption( "--aircraft=" );
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, "Incorrect path in configuration file.");
415 d_path.append(d_path_str);
416 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
419 SGPropertyNode *strings = c_node->getNode("strings");
421 readProperties(d_path.str(), strings);
422 } catch (const sg_exception &e) {
423 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
428 // Load the language specific strings
430 if (c_node != d_node) {
431 SGPath c_path( globals->get_fg_root() );
433 const char *c_path_str = c_node->getStringValue("strings");
435 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
439 c_path.append(c_path_str);
440 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
444 readProperties(c_path.str(), strings);
445 } catch (const sg_exception &e) {
446 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
456 // Initialize the localization routines
457 bool fgDetectLanguage() {
458 char *language = ::getenv("LANG");
460 if (language == NULL) {
461 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
465 SGPropertyNode *locale = fgInitLocale(language);
467 SG_LOG(SG_GENERAL, SG_ALERT,
468 "No internationalization settings specified in preferences.xml" );
473 globals->set_locale( locale );
478 // Attempt to locate and parse the various non-XML config files in order
479 // from least precidence to greatest precidence
481 do_options (int argc, char ** argv)
483 // Check for $fg_root/system.fgfsrc
484 SGPath config( globals->get_fg_root() );
485 config.append( "system.fgfsrc" );
486 fgParseOptions(config.str());
488 #if defined( unix ) || defined( __CYGWIN__ )
489 config.concat( "." );
490 config.concat( hostname );
491 fgParseOptions(config.str());
494 // Check for ~/.fgfsrc
495 if ( homedir != NULL ) {
496 config.set( homedir );
497 config.append( ".fgfsrc" );
498 fgParseOptions(config.str());
501 #if defined( unix ) || defined( __CYGWIN__ )
502 // Check for ~/.fgfsrc.hostname
503 config.concat( "." );
504 config.concat( hostname );
505 fgParseOptions(config.str());
508 // Parse remaining command line options
509 // These will override anything specified in a config file
510 fgParseArgs(argc, argv);
514 static string fgFindAircraftPath( const SGPath &path, const string &aircraft ) {
516 ulDir *dirp = ulOpenDir(path.str().c_str());
518 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
522 while ((dire = ulReadDir(dirp)) != NULL) {
524 if ( strcmp("CVS", dire->d_name) && strcmp(".", dire->d_name)
525 && strcmp("..", dire->d_name) )
528 next.append(dire->d_name);
530 string result = fgFindAircraftPath( next, aircraft );
531 if ( ! result.empty() ) {
535 } else if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
546 // Read in configuration (file and command line)
547 bool fgInitConfig ( int argc, char **argv ) {
549 // First, set some sane default values
552 // Read global preferences from $FG_ROOT/preferences.xml
553 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
554 fgLoadProps("preferences.xml", globals->get_props());
555 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
557 // Detect the required language as early as possible
558 if ( !fgDetectLanguage() ) {
562 // Scan user config files and command line for a specified aircraft.
563 fgInitFGAircraft(argc, argv);
565 string aircraft = fgGetString( "/sim/aircraft", "" );
566 if ( aircraft.size() > 0 ) {
567 SGPath aircraft_search( globals->get_fg_root() );
568 aircraft_search.append( "Aircraft" );
570 string aircraft_set = aircraft + "-set.xml";
572 string result = fgFindAircraftPath( aircraft_search, aircraft_set );
573 if ( !result.empty() ) {
574 fgSetString( "/sim/aircraft-dir", result.c_str() );
575 SGPath full_name( result );
576 full_name.append( aircraft_set );
578 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
579 << " from " << full_name.str());
581 readProperties( full_name.str(), globals->get_props() );
582 } catch ( const sg_exception &e ) {
583 string message = "Error reading default aircraft: ";
584 message += e.getFormattedMessage();
585 SG_LOG(SG_INPUT, SG_ALERT, message);
589 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
595 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
599 char *envp = ::getenv( "APPDATA" );
601 SGPath config( envp );
602 config.append( "flightgear.org" );
604 if ( homedir != NULL ) {
605 SGPath config( homedir );
606 config.append( ".fgfs" );
608 config.append( "preferences.xml" );
609 SG_LOG(SG_INPUT, SG_INFO, "Reading user preferences");
611 fgLoadProps(config.str().c_str(), globals->get_props(), false,
612 SGPropertyNode::USERARCHIVE);
614 SG_LOG(SG_INPUT, SG_BULK, "First time reading user preferences.");
616 SG_LOG(SG_INPUT, SG_BULK, "Finished Reading user preferences");
619 // parse options after loading aircraft to ensure any user
620 // overrides of defaults are honored.
621 do_options(argc, argv);
632 // This function is never used, but maybe useful in the future ???
635 // Preset lon/lat given an airport id
636 static bool fgSetPosFromAirportID( const string& id ) {
640 SG_LOG( SG_GENERAL, SG_INFO,
641 "Attempting to set starting position from airport code " << id );
643 if ( fgFindAirportID( id, &a ) ) {
645 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
646 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
648 // other code depends on the actual postition being set so set
650 fgSetDouble("/position/longitude-deg", a->longitude );
651 fgSetDouble("/position/latitude-deg", a->latitude );
653 SG_LOG( SG_GENERAL, SG_INFO,
654 "Position for " << id << " is (" << a->longitude
655 << ", " << a->latitude << ")" );
665 // Set current tower position lon/lat given an airport id
666 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
668 // tower height hard coded for now...
669 float towerheight=50.0f;
671 // make a little off the heading for 1 runway airports...
672 float fudge_lon = fabs(sin(hdg)) * .003f;
673 float fudge_lat = .003f - fudge_lon;
675 const FGAirport *a = fgFindAirportID( id);
677 fgSetDouble("/sim/tower/longitude-deg", a->getLongitude() + fudge_lon);
678 fgSetDouble("/sim/tower/latitude-deg", a->getLatitude() + fudge_lat);
679 fgSetDouble("/sim/tower/altitude-ft", a->getElevation() + towerheight);
687 struct FGTowerLocationListener : SGPropertyChangeListener {
688 void valueChanged(SGPropertyNode* node) {
689 const double hdg = fgGetDouble( "/orientation/heading-deg", 0);
690 const string id(node->getStringValue());
691 fgSetTowerPosFromAirportID(id, hdg);
695 static void fgInitTowerLocationListener() {
696 fgGetNode("/sim/tower/airport-id", true)
697 ->addChangeListener( new FGTowerLocationListener() );
700 // Set current_options lon/lat given an airport id and heading (degrees)
701 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
705 // set initial position from runway and heading
707 SG_LOG( SG_GENERAL, SG_INFO,
708 "Attempting to set starting position from airport code "
709 << id << " heading " << tgt_hdg );
711 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
712 SG_LOG( SG_GENERAL, SG_ALERT,
713 "Failed to find a good runway for " << id << '\n' );
720 double lat2, lon2, az2;
721 double heading = r._heading;
722 double azimuth = heading + 180.0;
723 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
725 SG_LOG( SG_GENERAL, SG_INFO,
726 "runway = " << r._lon << ", " << r._lat
727 << " length = " << r._length * SG_FEET_TO_METER
728 << " heading = " << azimuth );
730 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
731 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
732 &lat2, &lon2, &az2 );
734 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
736 double odist = fgGetDouble("/sim/presets/offset-distance");
737 odist *= SG_NM_TO_METER;
738 double oaz = azimuth;
739 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
740 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
743 while ( oaz >= 360.0 ) { oaz -= 360.0; }
744 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
750 fgSetDouble("/sim/presets/longitude-deg", lon2 );
751 fgSetDouble("/sim/presets/latitude-deg", lat2 );
752 fgSetDouble("/sim/presets/heading-deg", heading );
754 // other code depends on the actual values being set ...
755 fgSetDouble("/position/longitude-deg", lon2 );
756 fgSetDouble("/position/latitude-deg", lat2 );
757 fgSetDouble("/orientation/heading-deg", heading );
759 SG_LOG( SG_GENERAL, SG_INFO,
760 "Position for " << id << " is ("
762 << lat2 << ") new heading is "
769 // Set current_options lon/lat given an airport id and runway number
770 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
774 // set initial position from airport and runway number
776 SG_LOG( SG_GENERAL, SG_INFO,
777 "Attempting to set starting position for "
778 << id << ":" << rwy );
780 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
781 SG_LOG( SG_GENERAL, SG_ALERT,
782 "Failed to find runway " << rwy <<
783 " at airport " << id );
790 double lat2, lon2, az2;
791 double heading = r._heading;
792 double azimuth = heading + 180.0;
793 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
795 SG_LOG( SG_GENERAL, SG_INFO,
796 "runway = " << r._lon << ", " << r._lat
797 << " length = " << r._length * SG_FEET_TO_METER
798 << " heading = " << azimuth );
800 geo_direct_wgs_84 ( 0, r._lat, r._lon,
802 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
803 &lat2, &lon2, &az2 );
805 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
808 double odist = fgGetDouble("/sim/presets/offset-distance");
809 odist *= SG_NM_TO_METER;
810 double oaz = azimuth;
811 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
813 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
814 heading = fgGetDouble("/sim/presets/heading-deg");
816 while ( oaz >= 360.0 ) { oaz -= 360.0; }
817 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
823 fgSetDouble("/sim/presets/longitude-deg", lon2 );
824 fgSetDouble("/sim/presets/latitude-deg", lat2 );
825 fgSetDouble("/sim/presets/heading-deg", heading );
827 // other code depends on the actual values being set ...
828 fgSetDouble("/position/longitude-deg", lon2 );
829 fgSetDouble("/position/latitude-deg", lat2 );
830 fgSetDouble("/orientation/heading-deg", heading );
832 SG_LOG( SG_GENERAL, SG_INFO,
833 "Position for " << id << " is ("
835 << lat2 << ") new heading is "
842 static void fgSetDistOrAltFromGlideSlope() {
843 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
844 string apt_id = fgGetString("/sim/presets/airport-id");
845 double gs = fgGetDouble("/sim/presets/glideslope-deg")
846 * SG_DEGREES_TO_RADIANS ;
847 double od = fgGetDouble("/sim/presets/offset-distance");
848 double alt = fgGetDouble("/sim/presets/altitude-ft");
850 double apt_elev = 0.0;
851 if ( ! apt_id.empty() ) {
852 apt_elev = fgGetAirportElev( apt_id );
853 if ( apt_elev < -9990.0 ) {
860 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
861 // set altitude from glideslope and offset-distance
862 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
863 alt = fabs(od*tan(gs)) + apt_elev;
864 fgSetDouble("/sim/presets/altitude-ft", alt);
865 fgSetBool("/sim/presets/onground", false);
866 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
868 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
869 // set offset-distance from glideslope and altitude
870 od = (alt - apt_elev) / tan(gs);
871 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
872 fgSetDouble("/sim/presets/offset-distance", od);
873 fgSetBool("/sim/presets/onground", false);
874 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
876 } else if( fabs(gs) > 0.01 ) {
877 SG_LOG( SG_GENERAL, SG_ALERT,
878 "Glideslope given but not altitude or offset-distance." );
879 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
880 fgSetDouble("/sim/presets/glideslope-deg", 0);
881 fgSetBool("/sim/presets/onground", true);
886 // Set current_options lon/lat given an airport id and heading (degrees)
887 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
889 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
891 // set initial position from runway and heading
893 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
894 << id << ":" << freq );
896 double lon = nav->get_lon();
897 double lat = nav->get_lat();
899 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
901 double odist = fgGetDouble("/sim/presets/offset-distance")
903 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
905 while ( oaz >= 360.0 ) { oaz -= 360.0; }
906 double olat, olon, az2;
907 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
914 fgSetDouble("/sim/presets/longitude-deg", lon );
915 fgSetDouble("/sim/presets/latitude-deg", lat );
917 // other code depends on the actual values being set ...
918 fgSetDouble("/position/longitude-deg", lon );
919 fgSetDouble("/position/latitude-deg", lat );
920 fgSetDouble("/orientation/heading-deg",
921 fgGetDouble("/sim/presets/heading-deg") );
923 SG_LOG( SG_GENERAL, SG_INFO,
924 "Position for " << id << ":" << freq << " is ("
925 << lon << ", "<< lat << ")" );
929 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
930 << id << ":" << freq );
935 // Set current_options lon/lat given an aircraft carrier id
936 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
938 // set initial position from runway and heading
942 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
943 double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
944 double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
945 double alt = geodPos.elev() * SG_METER_TO_FEET;
947 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
948 << carrier << " at lat = " << lat << ", lon = " << lon
949 << ", alt = " << alt << ", heading = " << heading);
951 fgSetDouble("/sim/presets/longitude-deg", lon);
952 fgSetDouble("/sim/presets/latitude-deg", lat);
953 fgSetDouble("/sim/presets/altitude-ft", alt);
954 fgSetDouble("/sim/presets/heading-deg", heading);
955 fgSetDouble("/position/longitude-deg", lon);
956 fgSetDouble("/position/latitude-deg", lat);
957 fgSetDouble("/position/altitude-ft", alt);
958 fgSetDouble("/orientation/heading-deg", heading);
960 fgSetString("/sim/presets/speed-set", "UVW");
961 fgSetDouble("/velocities/uBody-fps", uvw[0]);
962 fgSetDouble("/velocities/vBody-fps", uvw[1]);
963 fgSetDouble("/velocities/wBody-fps", uvw[2]);
964 fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
965 fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
966 fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
968 fgSetBool("/sim/presets/onground", true);
972 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
978 // Set current_options lon/lat given an airport id and heading (degrees)
979 static bool fgSetPosFromFix( const string& id ) {
982 // set initial position from runway and heading
983 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
984 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
987 double lon = fix.get_lon();
988 double lat = fix.get_lat();
990 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
992 double odist = fgGetDouble("/sim/presets/offset-distance")
994 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
996 while ( oaz >= 360.0 ) { oaz -= 360.0; }
997 double olat, olon, az2;
998 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1005 fgSetDouble("/sim/presets/longitude-deg", lon );
1006 fgSetDouble("/sim/presets/latitude-deg", lat );
1008 // other code depends on the actual values being set ...
1009 fgSetDouble("/position/longitude-deg", lon );
1010 fgSetDouble("/position/latitude-deg", lat );
1011 fgSetDouble("/orientation/heading-deg",
1012 fgGetDouble("/sim/presets/heading-deg") );
1014 SG_LOG( SG_GENERAL, SG_INFO,
1015 "Position for " << id << " is ("
1016 << lon << ", "<< lat << ")" );
1020 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1026 static void parseWaypoints() {
1027 string_list *waypoints = globals->get_initial_waypoints();
1029 vector<string>::iterator i;
1030 for (i = waypoints->begin();
1031 i != waypoints->end();
1036 // Now were done using the way points we can deallocate the
1038 while (waypoints->begin() != waypoints->end()) {
1039 waypoints->pop_back();
1042 globals->set_initial_waypoints(0);
1051 * Initialize vor/ndb/ils/fix list management and query systems (as
1052 * well as simple airport db list)
1057 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1059 SGPath aptdb( globals->get_fg_root() );
1060 aptdb.append( "Airports/apt.dat" );
1062 SGPath p_metar( globals->get_fg_root() );
1063 p_metar.append( "Airports/metar.dat" );
1065 FGAirportList *airports = new FGAirportList();
1066 globals->set_airports( airports );
1067 FGRunwayList *runways = new FGRunwayList();
1068 globals->set_runways( runways );
1070 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1072 FGNavList *navlist = new FGNavList;
1073 FGNavList *loclist = new FGNavList;
1074 FGNavList *gslist = new FGNavList;
1075 FGNavList *dmelist = new FGNavList;
1076 FGNavList *mkrlist = new FGNavList;
1077 FGNavList *tacanlist = new FGNavList;
1078 FGNavList *carrierlist = new FGNavList;
1079 FGTACANList *channellist = new FGTACANList;
1081 globals->set_navlist( navlist );
1082 globals->set_loclist( loclist );
1083 globals->set_gslist( gslist );
1084 globals->set_dmelist( dmelist );
1085 globals->set_mkrlist( mkrlist );
1086 globals->set_tacanlist( tacanlist );
1087 globals->set_carrierlist( carrierlist );
1088 globals->set_channellist( channellist );
1090 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1091 SG_LOG( SG_GENERAL, SG_ALERT,
1092 "Problems loading one or more navigational database" );
1095 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1096 // align all the localizers with their corresponding runways
1097 // since data sources are good for cockpit navigation
1098 // purposes, but not always to the error tolerances needed to
1099 // exactly place these items.
1101 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1103 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1106 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1107 SGPath p_fix( globals->get_fg_root() );
1108 p_fix.append( "Navaids/fix.dat" );
1109 FGFixList *fixlist = new FGFixList;
1110 fixlist->init( p_fix );
1111 globals->set_fixlist( fixlist );
1117 // Set the initial position based on presets (or defaults)
1118 bool fgInitPosition() {
1119 // cout << "fgInitPosition()" << endl;
1120 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1121 * SG_DEGREES_TO_RADIANS ;
1122 double od = fgGetDouble("/sim/presets/offset-distance");
1123 double alt = fgGetDouble("/sim/presets/altitude-ft");
1125 bool set_pos = false;
1127 // If glideslope is specified, then calculate offset-distance or
1128 // altitude relative to glide slope if either of those was not
1130 if ( fabs( gs ) > 0.01 ) {
1131 fgSetDistOrAltFromGlideSlope();
1135 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1136 // If not, check for an airport-id and use that.
1137 // If not, default to the middle of the KSFO field.
1138 // The default values for lon/lat are deliberately out of range
1139 // so that the airport-id can take effect; valid lon/lat will
1140 // override airport-id, however.
1141 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1142 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1143 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1144 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1149 string apt = fgGetString("/sim/presets/airport-id");
1150 string rwy_no = fgGetString("/sim/presets/runway");
1151 double hdg = fgGetDouble("/sim/presets/heading-deg");
1152 string vor = fgGetString("/sim/presets/vor-id");
1153 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1154 string ndb = fgGetString("/sim/presets/ndb-id");
1155 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1156 string carrier = fgGetString("/sim/presets/carrier");
1157 string parkpos = fgGetString("/sim/presets/parkpos");
1158 string fix = fgGetString("/sim/presets/fix");
1160 fgSetDouble( "/orientation/heading-deg", hdg );
1161 fgInitTowerLocationListener();
1163 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1164 // An airport + runway is requested
1165 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1166 // set tower position (a little off the heading for single
1168 fgSetString("/sim/tower/airport-id", apt.c_str());
1173 if ( !set_pos && !apt.empty() ) {
1174 // An airport is requested (find runway closest to hdg)
1175 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1176 // set tower position (a little off the heading for single
1178 fgSetString("/sim/tower/airport-id", apt.c_str());
1183 if ( !set_pos && !vor.empty() ) {
1184 // a VOR is requested
1185 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1190 if ( !set_pos && !ndb.empty() ) {
1191 // an NDB is requested
1192 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1197 if ( !set_pos && !carrier.empty() ) {
1198 // an aircraft carrier is requested
1199 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1204 if ( !set_pos && !fix.empty() ) {
1205 // a Fix is requested
1206 if ( fgSetPosFromFix( fix ) ) {
1212 // No lon/lat specified, no airport specified, default to
1213 // middle of KSFO field.
1214 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1215 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1218 fgSetDouble( "/position/longitude-deg",
1219 fgGetDouble("/sim/presets/longitude-deg") );
1220 fgSetDouble( "/position/latitude-deg",
1221 fgGetDouble("/sim/presets/latitude-deg") );
1223 // determine if this should be an on-ground or in-air start
1224 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1225 fgSetBool("/sim/presets/onground", false);
1227 fgSetBool("/sim/presets/onground", true);
1234 // General house keeping initializations
1235 bool fgInitGeneral() {
1238 #if defined(FX) && defined(XMESA)
1239 char *mesa_win_state;
1242 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1243 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1245 root = globals->get_fg_root();
1246 if ( ! root.length() ) {
1247 // No root path set? Then bail ...
1248 SG_LOG( SG_GENERAL, SG_ALERT,
1249 "Cannot continue without a path to the base package "
1250 << "being defined." );
1253 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1255 #if defined(FX) && defined(XMESA)
1256 // initialize full screen flag
1257 globals->set_fullscreen(false);
1258 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1259 // Test for the MESA_GLX_FX env variable
1260 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1261 // test if we are fullscreen mesa/glide
1262 if ( (mesa_win_state[0] == 'f') ||
1263 (mesa_win_state[0] == 'F') ) {
1264 globals->set_fullscreen(true);
1274 // Initialize the flight model subsystem. This just creates the
1275 // object. The actual fdm initialization is delayed until we get a
1276 // proper scenery elevation hit. This is checked for in main.cxx
1280 if ( cur_fdm_state ) {
1281 delete cur_fdm_state;
1285 double dt = 1.0 / fgGetInt("/sim/model-hz");
1286 string model = fgGetString("/sim/flight-model");
1289 if ( model == "larcsim" ) {
1290 cur_fdm_state = new FGLaRCsim( dt );
1291 } else if ( model == "jsb" ) {
1292 cur_fdm_state = new FGJSBsim( dt );
1294 } else if ( model == "ada" ) {
1295 cur_fdm_state = new FGADA( dt );
1296 } else if ( model == "acms" ) {
1297 cur_fdm_state = new FGACMS( dt );
1299 } else if ( model == "balloon" ) {
1300 cur_fdm_state = new FGBalloonSim( dt );
1301 } else if ( model == "magic" ) {
1302 cur_fdm_state = new FGMagicCarpet( dt );
1303 } else if ( model == "ufo" ) {
1304 cur_fdm_state = new FGUFO( dt );
1305 } else if ( model == "external" ) {
1306 // external is a synonym for "--fdm=null" and is
1307 // maintained here for backwards compatibility
1308 cur_fdm_state = new FGNullFDM( dt );
1309 } else if ( model.find("network") == 0 ) {
1310 string host = "localhost";
1314 string net_options = model.substr(8);
1315 string::size_type begin, end;
1318 end = net_options.find( ",", begin );
1319 if ( end != string::npos ) {
1320 host = net_options.substr(begin, end - begin);
1324 end = net_options.find( ",", begin );
1325 if ( end != string::npos ) {
1326 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1330 end = net_options.find( ",", begin );
1331 if ( end != string::npos ) {
1332 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1336 end = net_options.find( ",", begin );
1337 if ( end != string::npos ) {
1338 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1341 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1342 } else if ( model.find("pipe") == 0 ) {
1343 // /* old */ string pipe_path = model.substr(5);
1344 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1345 string pipe_path = "";
1346 string pipe_protocol = "";
1347 string pipe_options = model.substr(5);
1348 string::size_type begin, end;
1351 end = pipe_options.find( ",", begin );
1352 if ( end != string::npos ) {
1353 pipe_path = pipe_options.substr(begin, end - begin);
1356 // protocol (last option)
1357 pipe_protocol = pipe_options.substr(begin);
1358 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1359 } else if ( model == "null" ) {
1360 cur_fdm_state = new FGNullFDM( dt );
1361 } else if ( model == "yasim" ) {
1362 cur_fdm_state = new YASim( dt );
1364 SG_LOG(SG_GENERAL, SG_ALERT,
1365 "Unrecognized flight model '" << model
1366 << "', cannot init flight dynamics model.");
1370 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1375 static void printMat(const sgVec4 *mat, char *name="")
1378 SG_LOG(SG_GENERAL, SG_BULK, name );
1379 for(i=0; i<4; i++) {
1380 SG_LOG(SG_GENERAL, SG_BULK, " " << mat[i][0] << " " << mat[i][1]
1381 << " " << mat[i][2] << " " << mat[i][3] );
1385 // Initialize view parameters
1387 // force update of model so that viewer can get some data...
1388 globals->get_aircraft_model()->update(0);
1389 // run update for current view so that data is current...
1390 globals->get_viewmgr()->update(0);
1392 printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1393 printMat(globals->get_current_view()->get_UP(),"UP");
1394 // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1399 SGTime *fgInitTime() {
1401 static const SGPropertyNode *longitude
1402 = fgGetNode("/position/longitude-deg");
1403 static const SGPropertyNode *latitude
1404 = fgGetNode("/position/latitude-deg");
1405 static const SGPropertyNode *cur_time_override
1406 = fgGetNode("/sim/time/cur-time-override", true);
1408 SGPath zone( globals->get_fg_root() );
1409 zone.append( "Timezone" );
1410 SGTime *t = new SGTime( longitude->getDoubleValue()
1411 * SGD_DEGREES_TO_RADIANS,
1412 latitude->getDoubleValue()
1413 * SGD_DEGREES_TO_RADIANS,
1415 cur_time_override->getLongValue() );
1417 globals->set_warp_delta( 0 );
1419 t->update( 0.0, 0.0,
1420 cur_time_override->getLongValue(),
1421 globals->get_warp() );
1427 // set up a time offset (aka warp) if one is specified
1428 void fgInitTimeOffset() {
1429 static const SGPropertyNode *longitude
1430 = fgGetNode("/position/longitude-deg");
1431 static const SGPropertyNode *latitude
1432 = fgGetNode("/position/latitude-deg");
1433 static const SGPropertyNode *cur_time_override
1434 = fgGetNode("/sim/time/cur-time-override", true);
1436 // Handle potential user specified time offsets
1437 int orig_warp = globals->get_warp();
1438 SGTime *t = globals->get_time_params();
1439 time_t cur_time = t->get_cur_time();
1440 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1441 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1442 time_t aircraftLocalTime =
1443 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1445 // Okay, we now have several possible scenarios
1446 int offset = fgGetInt("/sim/startup/time-offset");
1447 string offset_type = fgGetString("/sim/startup/time-offset-type");
1450 if ( offset_type == "real" ) {
1452 } else if ( offset_type == "dawn" ) {
1453 warp = fgTimeSecondsUntilSunAngle( cur_time,
1454 longitude->getDoubleValue()
1455 * SGD_DEGREES_TO_RADIANS,
1456 latitude->getDoubleValue()
1457 * SGD_DEGREES_TO_RADIANS,
1459 } else if ( offset_type == "morning" ) {
1460 warp = fgTimeSecondsUntilSunAngle( cur_time,
1461 longitude->getDoubleValue()
1462 * SGD_DEGREES_TO_RADIANS,
1463 latitude->getDoubleValue()
1464 * SGD_DEGREES_TO_RADIANS,
1466 } else if ( offset_type == "noon" ) {
1467 warp = fgTimeSecondsUntilSunAngle( cur_time,
1468 longitude->getDoubleValue()
1469 * SGD_DEGREES_TO_RADIANS,
1470 latitude->getDoubleValue()
1471 * SGD_DEGREES_TO_RADIANS,
1473 } else if ( offset_type == "afternoon" ) {
1474 warp = fgTimeSecondsUntilSunAngle( cur_time,
1475 longitude->getDoubleValue()
1476 * SGD_DEGREES_TO_RADIANS,
1477 latitude->getDoubleValue()
1478 * SGD_DEGREES_TO_RADIANS,
1480 } else if ( offset_type == "dusk" ) {
1481 warp = fgTimeSecondsUntilSunAngle( cur_time,
1482 longitude->getDoubleValue()
1483 * SGD_DEGREES_TO_RADIANS,
1484 latitude->getDoubleValue()
1485 * SGD_DEGREES_TO_RADIANS,
1487 } else if ( offset_type == "evening" ) {
1488 warp = fgTimeSecondsUntilSunAngle( cur_time,
1489 longitude->getDoubleValue()
1490 * SGD_DEGREES_TO_RADIANS,
1491 latitude->getDoubleValue()
1492 * SGD_DEGREES_TO_RADIANS,
1494 } else if ( offset_type == "midnight" ) {
1495 warp = fgTimeSecondsUntilSunAngle( cur_time,
1496 longitude->getDoubleValue()
1497 * SGD_DEGREES_TO_RADIANS,
1498 latitude->getDoubleValue()
1499 * SGD_DEGREES_TO_RADIANS,
1501 } else if ( offset_type == "system-offset" ) {
1503 } else if ( offset_type == "gmt-offset" ) {
1504 warp = offset - (currGMT - systemLocalTime);
1505 } else if ( offset_type == "latitude-offset" ) {
1506 warp = offset - (aircraftLocalTime - systemLocalTime);
1507 } else if ( offset_type == "system" ) {
1508 warp = offset - cur_time;
1509 } else if ( offset_type == "gmt" ) {
1510 warp = offset - currGMT;
1511 } else if ( offset_type == "latitude" ) {
1512 warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time;
1514 SG_LOG( SG_GENERAL, SG_ALERT,
1515 "FG_TIME::Unsupported offset type " << offset_type );
1518 globals->set_warp( orig_warp + warp );
1519 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1520 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1521 cur_time_override->getLongValue(),
1522 globals->get_warp() );
1524 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1525 << globals->get_warp() );
1529 // This is the top level init routine which calls all the other
1530 // initialization routines. If you are adding a subsystem to flight
1531 // gear, its initialization call should located in this routine.
1532 // Returns non-zero if a problem encountered.
1533 bool fgInitSubsystems() {
1534 // static const SGPropertyNode *longitude
1535 // = fgGetNode("/sim/presets/longitude-deg");
1536 // static const SGPropertyNode *latitude
1537 // = fgGetNode("/sim/presets/latitude-deg");
1538 // static const SGPropertyNode *altitude
1539 // = fgGetNode("/sim/presets/altitude-ft");
1540 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1541 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1543 ////////////////////////////////////////////////////////////////////
1544 // Initialize the event manager subsystem.
1545 ////////////////////////////////////////////////////////////////////
1547 globals->get_event_mgr()->init();
1548 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1550 ////////////////////////////////////////////////////////////////////
1551 // Initialize the property interpolator subsystem
1552 ////////////////////////////////////////////////////////////////////
1553 globals->add_subsystem("interpolator", new SGInterpolator);
1556 ////////////////////////////////////////////////////////////////////
1557 // Add the FlightGear property utilities.
1558 ////////////////////////////////////////////////////////////////////
1559 globals->add_subsystem("properties", new FGProperties);
1561 ////////////////////////////////////////////////////////////////////
1562 // Initialize the material property subsystem.
1563 ////////////////////////////////////////////////////////////////////
1565 SGPath mpath( globals->get_fg_root() );
1566 mpath.append( "materials.xml" );
1567 string season = fgGetString("/sim/startup/season", "summer");
1568 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str()) ) {
1569 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1574 ////////////////////////////////////////////////////////////////////
1575 // Initialize the scenery management subsystem.
1576 ////////////////////////////////////////////////////////////////////
1578 if ( globals->get_tile_mgr()->init() ) {
1579 // Load the local scenery data
1580 double visibility_meters = fgGetDouble("/environment/visibility-m");
1582 globals->get_tile_mgr()->update( visibility_meters );
1584 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1588 // cause refresh of viewer scenery timestamps every 15 seconds...
1589 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1590 globals->get_tile_mgr(),
1591 &FGTileMgr::refresh_view_timestamps,
1595 ////////////////////////////////////////////////////////////////////
1596 // Initialize the flight model subsystem.
1597 ////////////////////////////////////////////////////////////////////
1601 // allocates structures so must happen before any of the flight
1602 // model or control parameters are set
1603 fgAircraftInit(); // In the future this might not be the case.
1606 ////////////////////////////////////////////////////////////////////
1607 // Initialize the XML Autopilot subsystem.
1608 ////////////////////////////////////////////////////////////////////
1610 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1611 globals->add_subsystem( "route-manager", new FGRouteMgr );
1614 ////////////////////////////////////////////////////////////////////
1615 // Initialize the view manager subsystem.
1616 ////////////////////////////////////////////////////////////////////
1620 ////////////////////////////////////////////////////////////////////
1621 // Create and register the logger.
1622 ////////////////////////////////////////////////////////////////////
1624 globals->add_subsystem("logger", new FGLogger);
1626 ////////////////////////////////////////////////////////////////////
1627 // Create and register the XML GUI.
1628 ////////////////////////////////////////////////////////////////////
1630 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1633 ////////////////////////////////////////////////////////////////////
1634 // Initialize the local time subsystem.
1635 ////////////////////////////////////////////////////////////////////
1637 // update the current timezone each 30 minutes
1638 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1639 &fgUpdateLocalTime, 30*60 );
1640 fgInitTimeOffset(); // the environment subsystem needs this
1643 ////////////////////////////////////////////////////////////////////
1644 // Initialize the weather subsystem.
1645 ////////////////////////////////////////////////////////////////////
1647 // Initialize the weather modeling subsystem
1648 globals->add_subsystem("environment", new FGEnvironmentMgr);
1651 ////////////////////////////////////////////////////////////////////
1652 // Initialize the lighting subsystem.
1653 ////////////////////////////////////////////////////////////////////
1655 globals->add_subsystem("lighting", new FGLight);
1657 //////////////////////////////////////////////////////////////////////
1658 // Initialize the 2D cloud subsystem.
1659 ////////////////////////////////////////////////////////////////////
1660 fgGetBool("/sim/rendering/bump-mapping", false);
1662 #ifdef ENABLE_AUDIO_SUPPORT
1663 ////////////////////////////////////////////////////////////////////
1664 // Initialize the sound subsystem.
1665 ////////////////////////////////////////////////////////////////////
1667 init_volume = fgGetFloat("/sim/sound/volume");
1668 fgSetFloat("/sim/sound/volume", 0.0f);
1669 globals->set_soundmgr(new SGSoundMgr);
1670 globals->get_soundmgr()->init();
1671 globals->get_soundmgr()->bind();
1674 ////////////////////////////////////////////////////////////////////
1675 // Initialize the sound-effects subsystem.
1676 ////////////////////////////////////////////////////////////////////
1678 globals->add_subsystem("fx", new FGFX);
1682 ////////////////////////////////////////////////////////////////////
1683 // Initialise ATC display system
1684 ////////////////////////////////////////////////////////////////////
1686 SG_LOG(SG_GENERAL, SG_INFO, " ATC Display");
1687 globals->set_ATC_display(new FGATCDisplay);
1688 globals->get_ATC_display()->init();
1690 ////////////////////////////////////////////////////////////////////
1691 // Initialise the ATC Manager
1692 ////////////////////////////////////////////////////////////////////
1694 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1695 globals->set_ATC_mgr(new FGATCMgr);
1696 globals->get_ATC_mgr()->init();
1698 ////////////////////////////////////////////////////////////////////
1699 // Initialise the AI Manager
1700 ////////////////////////////////////////////////////////////////////
1702 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1703 globals->set_AI_mgr(new FGAIMgr);
1704 globals->get_AI_mgr()->init();
1706 ////////////////////////////////////////////////////////////////////
1707 // Initialise the AI Model Manager
1708 ////////////////////////////////////////////////////////////////////
1709 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1710 globals->add_subsystem("ai_model", new FGAIManager);
1711 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1714 // It's probably a good idea to initialize the top level traffic manager
1715 // After the AI and ATC systems have been initialized properly.
1716 // AI Traffic manager
1717 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1718 FGTrafficManager *dispatcher =
1719 (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1720 SGPath path = globals->get_fg_root();
1721 path.append("/Traffic/fgtraffic.xml");
1724 //globals->get_subsystem("Traffic Manager")->init();
1726 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1727 globals->add_subsystem("systems", new FGSystemMgr);
1731 ////////////////////////////////////////////////////////////////////
1732 // Initialize the cockpit subsystem
1733 ////////////////////////////////////////////////////////////////////
1734 if( fgCockpitInit( ¤t_aircraft )) {
1735 // Cockpit initialized ok.
1737 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1742 ////////////////////////////////////////////////////////////////////
1743 // Initialize the autopilot subsystem.
1744 ////////////////////////////////////////////////////////////////////
1746 // FIXME: these should go in the
1747 // GUI initialization code, not here.
1748 // fgAPAdjustInit();
1749 NewTgtAirportInit();
1753 ////////////////////////////////////////////////////////////////////
1754 // Initialize I/O subsystem.
1755 ////////////////////////////////////////////////////////////////////
1757 globals->get_io()->init();
1758 globals->get_io()->bind();
1761 ////////////////////////////////////////////////////////////////////
1762 // Add a new 2D panel.
1763 ////////////////////////////////////////////////////////////////////
1765 string panel_path = fgGetString("/sim/panel/path",
1766 "Panels/Default/default.xml");
1768 globals->set_current_panel( fgReadPanel(panel_path) );
1769 if (globals->get_current_panel() == 0) {
1770 SG_LOG( SG_INPUT, SG_ALERT,
1771 "Error reading new panel from " << panel_path );
1773 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1774 globals->get_current_panel()->init();
1775 globals->get_current_panel()->bind();
1779 ////////////////////////////////////////////////////////////////////
1780 // Initialize the controls subsystem.
1781 ////////////////////////////////////////////////////////////////////
1783 globals->get_controls()->init();
1784 globals->get_controls()->bind();
1787 ////////////////////////////////////////////////////////////////////
1788 // Initialize the input subsystem.
1789 ////////////////////////////////////////////////////////////////////
1791 globals->add_subsystem("input", new FGInput);
1794 ////////////////////////////////////////////////////////////////////
1795 // Initialize the replay subsystem
1796 ////////////////////////////////////////////////////////////////////
1797 globals->add_subsystem("replay", new FGReplay);
1799 ////////////////////////////////////////////////////////////////////
1800 // Bind and initialize subsystems.
1801 ////////////////////////////////////////////////////////////////////
1803 globals->get_subsystem_mgr()->bind();
1804 globals->get_subsystem_mgr()->init();
1806 #ifdef FG_MPLAYER_AS
1807 ////////////////////////////////////////////////////////////////////
1808 // Initialize multiplayer subsystem
1809 ////////////////////////////////////////////////////////////////////
1811 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1812 globals->get_multiplayer_mgr()->init();
1815 ////////////////////////////////////////////////////////////////////////
1816 // Initialize the Nasal interpreter.
1817 // Do this last, so that the loaded scripts see initialized state
1818 ////////////////////////////////////////////////////////////////////////
1819 FGNasalSys* nasal = new FGNasalSys();
1820 globals->add_subsystem("nasal", nasal);
1823 ////////////////////////////////////////////////////////////////////
1824 // At this point we could try and parse the waypoint options
1825 ///////////////////////////////////////////////////////////////////
1828 // initialize methods that depend on other subsystems.
1829 globals->get_subsystem_mgr()->postinit();
1831 ////////////////////////////////////////////////////////////////////////
1832 // End of subsystem initialization.
1833 ////////////////////////////////////////////////////////////////////
1835 SG_LOG( SG_GENERAL, SG_INFO, endl);
1837 // Save the initial state for future
1839 globals->saveInitialState();
1845 void fgReInitSubsystems()
1847 // static const SGPropertyNode *longitude
1848 // = fgGetNode("/sim/presets/longitude-deg");
1849 // static const SGPropertyNode *latitude
1850 // = fgGetNode("/sim/presets/latitude-deg");
1851 static const SGPropertyNode *altitude
1852 = fgGetNode("/sim/presets/altitude-ft");
1853 static const SGPropertyNode *master_freeze
1854 = fgGetNode("/sim/freeze/master");
1856 SG_LOG( SG_GENERAL, SG_INFO,
1857 "fgReInitSubsystems(): /position/altitude = "
1858 << altitude->getDoubleValue() );
1860 bool freeze = master_freeze->getBoolValue();
1862 fgSetBool("/sim/freeze/master", true);
1864 fgSetBool("/sim/crashed", false);
1866 // Force reupdating the positions of the ai 3d models. They are used for
1867 // initializing ground level for the FDM.
1868 globals->get_subsystem("ai_model")->reinit();
1870 // Initialize the FDM
1873 // allocates structures so must happen before any of the flight
1874 // model or control parameters are set
1875 fgAircraftInit(); // In the future this might not be the case.
1877 // reload offsets from config defaults
1878 globals->get_viewmgr()->reinit();
1882 globals->get_controls()->reset_all();
1884 fgUpdateLocalTime();
1886 // re-init to proper time of day setting
1890 fgSetBool("/sim/freeze/master", false);
1892 fgSetBool("/sim/sceneryloaded",false);