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 #include <simgear/compiler.h>
32 #include <string.h> // strcmp()
34 #if defined(SG_WINDOWS)
35 # include <io.h> // isatty()
36 # include <process.h> // _getpid()
38 # define isatty _isatty
40 // for open() and options
41 # include <sys/types.h>
42 # include <sys/stat.h>
48 #include <boost/algorithm/string/compare.hpp>
49 #include <boost/algorithm/string/predicate.hpp>
51 #include <osgViewer/Viewer>
53 #include <simgear/canvas/Canvas.hxx>
54 #include <simgear/constants.h>
55 #include <simgear/debug/logstream.hxx>
56 #include <simgear/structure/exception.hxx>
57 #include <simgear/structure/event_mgr.hxx>
58 #include <simgear/structure/SGPerfMon.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/sg_dir.hxx>
61 #include <simgear/misc/sgstream.hxx>
62 #include <simgear/misc/strutils.hxx>
63 #include <simgear/props/props_io.hxx>
64 #include <simgear/scene/tsync/terrasync.hxx>
66 #include <simgear/scene/model/modellib.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/material/Effect.hxx>
69 #include <simgear/scene/model/particles.hxx>
70 #include <simgear/scene/tsync/terrasync.hxx>
72 #include <simgear/package/Root.hxx>
73 #include <simgear/package/Package.hxx>
74 #include <simgear/package/Install.hxx>
75 #include <simgear/package/Catalog.hxx>
77 #include <Aircraft/controls.hxx>
78 #include <Aircraft/replay.hxx>
79 #include <Aircraft/FlightHistory.hxx>
80 #include <Airports/runways.hxx>
81 #include <Airports/airport.hxx>
82 #include <Airports/dynamics.hxx>
84 #include <AIModel/AIManager.hxx>
86 #include <ATC/atc_mgr.hxx>
88 #include <Autopilot/route_mgr.hxx>
89 #include <Autopilot/autopilotgroup.hxx>
91 #include <Cockpit/panel.hxx>
92 #include <Cockpit/panel_io.hxx>
94 #include <Canvas/canvas_mgr.hxx>
95 #include <Canvas/gui_mgr.hxx>
96 #include <Canvas/FGCanvasSystemAdapter.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <GUI/MessageBox.hxx>
99 #include <Input/input.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 #include <Model/acmodel.hxx>
102 #include <Model/modelmgr.hxx>
103 #include <AIModel/submodel.hxx>
104 #include <AIModel/AIManager.hxx>
105 #include <Navaids/navdb.hxx>
106 #include <Navaids/navlist.hxx>
107 #include <Scenery/scenery.hxx>
108 #include <Scenery/SceneryPager.hxx>
109 #include <Scenery/tilemgr.hxx>
110 #include <Scripting/NasalSys.hxx>
111 #include <Sound/voice.hxx>
112 #include <Sound/soundmanager.hxx>
113 #include <Systems/system_mgr.hxx>
114 #include <Time/light.hxx>
115 #include <Time/TimeManager.hxx>
117 #include <Traffic/TrafficMgr.hxx>
118 #include <MultiPlayer/multiplaymgr.hxx>
119 #include <FDM/fdm_shell.hxx>
120 #include <Environment/ephemeris.hxx>
121 #include <Environment/environment_mgr.hxx>
122 #include <Viewer/renderer.hxx>
123 #include <Viewer/viewmgr.hxx>
124 #include <Viewer/FGEventHandler.hxx>
125 #include <Navaids/NavDataCache.hxx>
126 #include <Instrumentation/HUD/HUD.hxx>
127 #include <Cockpit/cockpitDisplayManager.hxx>
128 #include <Network/HTTPClient.hxx>
129 #include <Network/fgcom.hxx>
130 #include <Network/http/httpd.hxx>
131 #include <Include/version.h>
133 #include <Viewer/CameraGroup.hxx>
135 #include "fg_init.hxx"
137 #include "fg_commands.hxx"
138 #include "fg_props.hxx"
139 #include "FGInterpolator.hxx"
140 #include "options.hxx"
141 #include "globals.hxx"
142 #include "logger.hxx"
144 #include "positioninit.hxx"
146 #include "AircraftDirVisitorBase.hxx"
149 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
159 using namespace boost::algorithm;
160 using namespace simgear::pkg;
162 extern osg::ref_ptr<osgViewer::Viewer> viewer;
164 // Return the current base package version
165 string fgBasePackageVersion() {
166 SGPath base_path( globals->get_fg_root() );
167 base_path.append("version");
168 if (!base_path.exists()) {
172 sg_gzifstream in( base_path.str() );
183 class FindAndCacheAircraft : public AircraftDirVistorBase
186 FindAndCacheAircraft(SGPropertyNode* autoSave)
188 _cache = autoSave->getNode("sim/startup/path-cache", true);
193 std::string aircraft = fgGetString( "/sim/aircraft", "");
194 if (aircraft.empty()) {
195 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
196 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
200 _searchAircraft = aircraft + "-set.xml";
201 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
202 if (!aircraftDir.empty()) {
203 // aircraft-dir was set, skip any searching at all, if it's valid
204 simgear::Dir acPath(aircraftDir);
205 SGPath setFile = acPath.file(_searchAircraft);
206 if (setFile.exists()) {
207 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
210 readProperties(setFile.str(), globals->get_props());
211 } catch ( const sg_exception &e ) {
212 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
213 flightgear::fatalMessageBox("Error reading aircraft",
214 "An error occured reading the requested aircraft (" + aircraft + ")",
215 e.getFormattedMessage());
221 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
222 "' not found in specified dir:" << aircraftDir);
223 flightgear::fatalMessageBox("Aircraft not found",
224 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
231 // prepare cache for re-scan
232 SGPropertyNode *n = _cache->getNode("fg-root", true);
233 n->setStringValue(globals->get_fg_root().c_str());
234 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
235 n = _cache->getNode("fg-aircraft", true);
236 n->setStringValue(getAircraftPaths().c_str());
237 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
238 _cache->removeChildren("aircraft");
240 visitAircraftPaths();
243 if (_foundPath.str().empty()) {
244 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
245 flightgear::fatalMessageBox("Aircraft not found",
246 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
251 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
252 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
253 if (!_foundPath.exists()) {
254 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
259 readProperties(_foundPath.str(), globals->get_props());
260 } catch ( const sg_exception &e ) {
261 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
262 flightgear::fatalMessageBox("Error reading aircraft",
263 "An error occured reading the requested aircraft (" + aircraft + ")",
264 e.getFormattedMessage());
272 SGPath getAircraftPaths() {
273 string_list pathList = globals->get_aircraft_paths();
274 SGPath aircraftPaths;
275 string_list::const_iterator it = pathList.begin();
276 if (it != pathList.end()) {
277 aircraftPaths.set(*it);
280 for (; it != pathList.end(); ++it) {
281 aircraftPaths.add(*it);
283 return aircraftPaths;
288 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
289 return false; // cache mismatch
292 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
293 return false; // cache mismatch
296 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
297 for (unsigned int i = 0; i < cache.size(); i++) {
298 const char *name = cache[i]->getStringValue("file", "");
299 if (!boost::equals(_searchAircraft, name, is_iequal())) {
303 SGPath xml(cache[i]->getStringValue("path", ""));
311 } // of aircraft in cache iteration
316 virtual VisitResult visit(const SGPath& p)
321 if (!_cache->getChild("aircraft", i++, false))
325 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
327 std::string fileName(p.file());
328 n = entry->getNode("file", true);
329 n->setStringValue(fileName);
330 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
332 n = entry->getNode("path", true);
333 n->setStringValue(p.dir());
334 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
336 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
341 return VISIT_CONTINUE;
344 std::string _searchAircraft;
346 SGPropertyNode* _cache;
350 static SGPath platformDefaultDataPath()
352 char *envp = ::getenv( "APPDATA" );
353 SGPath config( envp );
354 config.append( "flightgear.org" );
358 #elif defined(SG_MAC)
360 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
363 static SGPath platformDefaultDataPath()
365 return SGPath::home() / ".fgfs";
371 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
372 globals->set_fg_home(dataPath.c_str());
374 simgear::Dir fgHome(dataPath);
375 if (!fgHome.exists()) {
379 if (!fgHome.exists()) {
380 flightgear::fatalMessageBox("Problem setting up user data",
381 "Unable to create the user-data storage folder at: '"
382 + dataPath.str() + "'");
386 if (fgGetBool("/sim/fghome-readonly", false)) {
387 // user / config forced us into readonly mode, fine
388 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
392 // write our PID, and check writeability
393 SGPath pidPath(dataPath, "fgfs.pid");
394 if (pidPath.exists()) {
395 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
396 // set a marker property so terrasync/navcache don't try to write
397 // from secondary instances
398 fgSetBool("/sim/fghome-readonly", true);
404 #if defined(SG_WINDOWS)
405 size_t len = snprintf(buf, 16, "%d", _getpid());
407 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
408 FILE_SHARE_READ, /* sharing */
409 NULL, /* security attributes */
410 CREATE_NEW, /* error if already exists */
411 FILE_FLAG_DELETE_ON_CLOSE,
412 NULL /* template */);
414 result = (f != INVALID_HANDLE_VALUE);
417 WriteFile(f, buf, len, &written, NULL /* overlapped */);
420 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
422 ssize_t len = snprintf(buf, 16, "%d", getpid());
423 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
425 result = ::write(fd, buf, len) == len;
426 if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
431 fgSetBool("/sim/fghome-readonly", false);
434 flightgear::fatalMessageBox("File permissions problem",
435 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
436 "User-data at:" + dataPath.str());
441 // Read in configuration (file and command line)
442 int fgInitConfig ( int argc, char **argv, bool reinit )
444 SGPath dataPath = globals->get_fg_home();
446 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
447 if (!exportDir.exists()) {
448 exportDir.create(0755);
451 // Set /sim/fg-home and don't allow malign code to override it until
452 // Nasal security is set up. Use FG_HOME if necessary.
453 SGPropertyNode *home = fgGetNode("/sim", true);
454 home->removeChild("fg-home", 0);
455 home = home->getChild("fg-home", 0, true);
456 home->setStringValue(dataPath.c_str());
457 home->setAttribute(SGPropertyNode::WRITE, false);
460 flightgear::Options* options = flightgear::Options::sharedInstance();
462 options->init(argc, argv, dataPath);
465 bool loadDefaults = options->shouldLoadDefaultConfig();
467 // Read global preferences from $FG_ROOT/preferences.xml
468 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
469 fgLoadProps("preferences.xml", globals->get_props());
470 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
472 // do not load user settings when reset to default is requested, or if
473 // told to explicitly ignore
474 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
476 SG_LOG(SG_GENERAL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
480 globals->loadUserSettings(dataPath);
483 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
484 }// of no-default-config selected
486 return flightgear::FG_OPTIONS_OK;
489 static void initAircraftDirsNasalSecurity()
491 SGPropertyNode* sim = fgGetNode("/sim", true);
492 sim->removeChildren("fg-aircraft");
495 string_list const aircraft_paths = globals->get_aircraft_paths();
496 for( string_list::const_iterator it = aircraft_paths.begin();
497 it != aircraft_paths.end();
500 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
501 n->setStringValue(*it);
502 n->setAttribute(SGPropertyNode::WRITE, false);
506 int fgInitAircraft(bool reinit)
509 // FIXME - use Documents/FlightGear/Aircraft
510 SGPath userAircraftDir = globals->get_fg_home();
511 userAircraftDir.append("Aircraft");
513 SGSharedPtr<Root> pkgRoot(new Root(userAircraftDir, FLIGHTGEAR_VERSION));
514 // set the http client later (too early in startup right now)
515 globals->setPackageRoot(pkgRoot);
518 SGSharedPtr<Root> pkgRoot(globals->packageRoot());
519 SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
520 aircraftProp->setAttribute(SGPropertyNode::PRESERVE, true);
523 flightgear::Options::sharedInstance()->initAircraft();
526 string aircraftId(aircraftProp->getStringValue());
527 PackageRef acftPackage = pkgRoot->getPackageById(aircraftId);
529 if (acftPackage->isInstalled()) {
530 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft from package:" << acftPackage->qualifiedId());
532 // set catalog path so intra-package dependencies within the catalog
533 // are resolved correctly.
534 globals->set_catalog_aircraft_path(acftPackage->catalog()->installRoot());
536 // set aircraft-dir to short circuit the search process
537 InstallRef acftInstall = acftPackage->install();
538 fgSetString("/sim/aircraft-dir", acftInstall->path().c_str());
540 // overwrite the fully qualified ID with the aircraft one, so the
541 // code in FindAndCacheAircraft works as normal
542 // note since we may be using a variant, we can't use the package ID
543 size_t lastDot = aircraftId.rfind('.');
544 if (lastDot != std::string::npos) {
545 aircraftId = aircraftId.substr(lastDot + 1);
546 aircraftProp->setStringValue(aircraftId);
549 // run the traditional-code path below
552 // naturally the better option would be to on-demand install it!
553 flightgear::fatalMessageBox("Aircraft not installed",
554 "Requested aircraft is not currently installed.",
557 return flightgear::FG_OPTIONS_ERROR;
562 initAircraftDirsNasalSecurity();
564 FindAndCacheAircraft f(globals->get_props());
565 if (!f.loadAircraft()) {
566 return flightgear::FG_OPTIONS_ERROR;
569 return flightgear::FG_OPTIONS_OK;
573 * Initialize vor/ndb/ils/fix list management and query systems (as
574 * well as simple airport db list)
575 * This is called multiple times in the case of a cache rebuild,
576 * to allow lengthy caching to take place in the background, without
577 * blocking the main/UI thread.
582 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
583 static bool doingRebuild = false;
584 if (doingRebuild || cache->isRebuildRequired()) {
586 bool finished = cache->rebuild();
588 // sleep to give the rebuild thread more time
589 SGTimeStamp::sleepForMSec(50);
594 FGTACANList *channellist = new FGTACANList;
595 globals->set_channellist( channellist );
597 SGPath path(globals->get_fg_root());
598 path.append( "Navaids/TACAN_freq.dat" );
599 flightgear::loadTacan(path, channellist);
604 // General house keeping initializations
605 bool fgInitGeneral() {
608 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
609 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
611 root = globals->get_fg_root();
612 if ( ! root.length() ) {
613 // No root path set? Then bail ...
614 SG_LOG( SG_GENERAL, SG_ALERT,
615 "Cannot continue without a path to the base package "
616 << "being defined." );
619 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
621 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
622 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
623 fgSetString("/sim/startup/browser-app", globals->get_browser());
625 simgear::Dir cwd(simgear::Dir::current());
626 SGPropertyNode *curr = fgGetNode("/sim", true);
627 curr->removeChild("fg-current", 0);
628 curr = curr->getChild("fg-current", 0, true);
629 curr->setStringValue(cwd.path().str());
630 curr->setAttribute(SGPropertyNode::WRITE, false);
632 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
633 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
637 // Write various configuraton values out to the logs
638 void fgOutputSettings()
640 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
641 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
643 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
644 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
645 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
647 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
648 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
651 // This is the top level init routine which calls all the other
652 // initialization routines. If you are adding a subsystem to flight
653 // gear, its initialization call should located in this routine.
654 // Returns non-zero if a problem encountered.
655 void fgCreateSubsystems(bool duringReset) {
657 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
658 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
660 ////////////////////////////////////////////////////////////////////
661 // Initialize the sound subsystem.
662 ////////////////////////////////////////////////////////////////////
663 // Sound manager uses an own subsystem group "SOUND" which is the last
664 // to be updated in every loop.
665 // Sound manager is updated last so it can use the CPU while the GPU
666 // is processing the scenery (doubled the frame-rate for me) -EMH-
667 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
669 ////////////////////////////////////////////////////////////////////
670 // Initialize the event manager subsystem.
671 ////////////////////////////////////////////////////////////////////
673 globals->get_event_mgr()->init();
674 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
676 ////////////////////////////////////////////////////////////////////
677 // Initialize the property interpolator subsystem. Put into the INIT
678 // group because the "nasal" subsystem may need it at GENERAL take-down.
679 ////////////////////////////////////////////////////////////////////
680 globals->add_subsystem("prop-interpolator", new FGInterpolator, SGSubsystemMgr::INIT);
683 ////////////////////////////////////////////////////////////////////
684 // Add the FlightGear property utilities.
685 ////////////////////////////////////////////////////////////////////
686 globals->add_subsystem("properties", new FGProperties);
689 ////////////////////////////////////////////////////////////////////
690 // Add the performance monitoring system.
691 ////////////////////////////////////////////////////////////////////
692 globals->add_subsystem("performance-mon",
693 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
694 fgGetNode("/sim/performance-monitor", true)));
696 ////////////////////////////////////////////////////////////////////
697 // Initialize the material property subsystem.
698 ////////////////////////////////////////////////////////////////////
700 SGPath mpath( globals->get_fg_root() );
701 mpath.append( fgGetString("/sim/rendering/materials-file") );
702 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
703 globals->get_props()) ) {
704 throw sg_io_exception("Error loading materials file", mpath);
707 globals->add_subsystem( "http", new FGHTTPClient );
709 ////////////////////////////////////////////////////////////////////
710 // Initialize the scenery management subsystem.
711 ////////////////////////////////////////////////////////////////////
713 globals->get_scenery()->get_scene_graph()
714 ->addChild(simgear::Particles::getCommonRoot());
715 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
717 ////////////////////////////////////////////////////////////////////
718 // Initialize the flight model subsystem.
719 ////////////////////////////////////////////////////////////////////
721 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
723 ////////////////////////////////////////////////////////////////////
724 // Initialize the weather subsystem.
725 ////////////////////////////////////////////////////////////////////
727 // Initialize the weather modeling subsystem
728 globals->add_subsystem("environment", new FGEnvironmentMgr);
729 globals->add_subsystem("ephemeris", new Ephemeris);
731 ////////////////////////////////////////////////////////////////////
732 // Initialize the aircraft systems and instrumentation (before the
734 ////////////////////////////////////////////////////////////////////
736 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
737 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
738 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
739 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
741 ////////////////////////////////////////////////////////////////////
742 // Initialize the XML Autopilot subsystem.
743 ////////////////////////////////////////////////////////////////////
745 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
746 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
747 globals->add_subsystem( "route-manager", new FGRouteMgr );
749 ////////////////////////////////////////////////////////////////////
750 // Initialize the Input-Output subsystem
751 ////////////////////////////////////////////////////////////////////
752 globals->add_subsystem( "io", new FGIO );
754 ////////////////////////////////////////////////////////////////////
755 // Create and register the logger.
756 ////////////////////////////////////////////////////////////////////
758 globals->add_subsystem("logger", new FGLogger);
760 ////////////////////////////////////////////////////////////////////
761 // Create and register the XML GUI.
762 ////////////////////////////////////////////////////////////////////
764 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
766 //////////////////////////////////////////////////////////////////////
767 // Initialize the 2D cloud subsystem.
768 ////////////////////////////////////////////////////////////////////
769 fgGetBool("/sim/rendering/bump-mapping", false);
771 ////////////////////////////////////////////////////////////////////
772 // Initialize the canvas 2d drawing subsystem.
773 ////////////////////////////////////////////////////////////////////
774 simgear::canvas::Canvas::setSystemAdapter(
775 simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
777 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
778 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
780 ////////////////////////////////////////////////////////////////////
781 // Initialize the ATC subsystem
782 ////////////////////////////////////////////////////////////////////
783 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
785 ////////////////////////////////////////////////////////////////////
786 // Initialize multiplayer subsystem
787 ////////////////////////////////////////////////////////////////////
789 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
791 ////////////////////////////////////////////////////////////////////
792 // Initialise the AI Model Manager
793 ////////////////////////////////////////////////////////////////////
794 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
795 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
796 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
799 // It's probably a good idea to initialize the top level traffic manager
800 // After the AI and ATC systems have been initialized properly.
801 // AI Traffic manager
802 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
804 ////////////////////////////////////////////////////////////////////
805 // Add a new 2D panel.
806 ////////////////////////////////////////////////////////////////////
808 fgSetArchivable("/sim/panel/visibility");
809 fgSetArchivable("/sim/panel/x-offset");
810 fgSetArchivable("/sim/panel/y-offset");
811 fgSetArchivable("/sim/panel/jitter");
813 ////////////////////////////////////////////////////////////////////
814 // Initialize the controls subsystem.
815 ////////////////////////////////////////////////////////////////////
817 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
819 ////////////////////////////////////////////////////////////////////
820 // Initialize the input subsystem.
821 ////////////////////////////////////////////////////////////////////
823 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
826 ////////////////////////////////////////////////////////////////////
827 // Initialize the replay subsystem
828 ////////////////////////////////////////////////////////////////////
829 globals->add_subsystem("replay", new FGReplay);
830 globals->add_subsystem("history", new FGFlightHistory);
832 #ifdef ENABLE_AUDIO_SUPPORT
833 ////////////////////////////////////////////////////////////////////
834 // Initialize the sound-effects subsystem.
835 ////////////////////////////////////////////////////////////////////
836 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
840 ////////////////////////////////////////////////////////////////////
841 // Initialize the FGCom subsystem.
842 ////////////////////////////////////////////////////////////////////
843 globals->add_subsystem("fgcom", new FGCom);
847 SGSubsystem * httpd = flightgear::http::FGHttpd::createInstance( fgGetNode(flightgear::http::PROPERTY_ROOT) );
849 globals->add_subsystem("httpd", httpd );
852 ////////////////////////////////////////////////////////////////////
853 // Initialize the lighting subsystem.
854 ////////////////////////////////////////////////////////////////////
856 // ordering here is important : Nasal (via events), then models, then views
858 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
859 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
862 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
863 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
865 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
867 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
868 SGSubsystemMgr::DISPLAY);
871 void fgPostInitSubsystems()
876 ////////////////////////////////////////////////////////////////////////
877 // Initialize the Nasal interpreter.
878 // Do this last, so that the loaded scripts see initialized state
879 ////////////////////////////////////////////////////////////////////////
880 FGNasalSys* nasal = new FGNasalSys();
881 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
883 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
885 // initialize methods that depend on other subsystems.
887 globals->get_subsystem_mgr()->postinit();
888 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
890 ////////////////////////////////////////////////////////////////////////
891 // End of subsystem initialization.
892 ////////////////////////////////////////////////////////////////////
894 fgSetBool("/sim/crashed", false);
895 fgSetBool("/sim/initialized", true);
897 SG_LOG( SG_GENERAL, SG_INFO, endl);
900 // re-position is a simplified version of the traditional (legacy)
901 // reset procedure. We only need to poke systems which will be upset by
902 // a sudden change in aircraft position. Since this potentially includes
903 // Nasal, we trigger the 'reinit' signal.
904 void fgStartReposition()
906 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
907 SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
909 // ensure we are frozen
910 bool freeze = master_freeze->getBoolValue();
912 master_freeze->setBoolValue(true);
915 // set this signal so Nasal scripts can take action.
916 fgSetBool("/sim/signals/reinit", true);
917 fgSetBool("/sim/crashed", false);
919 FDMShell* fdm = static_cast<FDMShell*>(globals->get_subsystem("flight"));
922 // update our position based on current presets
923 // this will mark position as needed finalized which we'll do in the
925 flightgear::initPosition();
927 simgear::SGTerraSync* terraSync =
928 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
930 terraSync->reposition();
933 // Initialize the FDM
934 globals->get_subsystem("flight")->reinit();
936 // reset replay buffers
937 globals->get_subsystem("replay")->reinit();
939 // ugly: finalizePosition waits for METAR to arrive for the new airport.
940 // we don't re-init the environment manager here, since historically we did
941 // not, and doing so seems to have other issues. All that's needed is to
942 // schedule METAR fetch immediately, so it's available for finalizePosition.
943 // So we manually extract the METAR-fetching component inside the environment
944 // manager, and re-init that.
945 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
947 envMgr->get_subsystem("realwx")->reinit();
950 // need to bind FDMshell again, since we manually unbound it above...
953 // need to reset aircraft (systems/instruments/autopilot)
954 // so they can adapt to current environment
955 globals->get_subsystem("systems")->reinit();
956 globals->get_subsystem("instrumentation")->reinit();
957 globals->get_subsystem("xml-autopilot")->reinit();
959 // setup state to end re-init
960 fgSetBool("/sim/signals/reinit", false);
962 master_freeze->setBoolValue(false);
964 fgSetBool("/sim/sceneryloaded",false);
967 void fgStartNewReset()
969 SGPropertyNode_ptr preserved(new SGPropertyNode);
971 if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
972 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
974 fgSetBool("/sim/signals/reinit", true);
975 fgSetBool("/sim/freeze/master", true);
977 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
978 // Nasal is manually inited in fgPostInit, ensure it's already shutdown
979 // before other subsystems, so Nasal listeners don't fire during shutdonw
980 SGSubsystem* nasal = subsystemManger->get_subsystem("nasal");
983 subsystemManger->remove("nasal");
985 subsystemManger->shutdown();
986 subsystemManger->unbind();
988 // remove most subsystems, with a few exceptions.
989 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
990 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
991 const string_list& names(grp->member_names());
992 string_list::const_iterator it;
993 for (it = names.begin(); it != names.end(); ++it) {
994 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
995 || (*it == "lighting"))
1001 subsystemManger->remove(it->c_str());
1002 } catch (std::exception& e) {
1003 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
1005 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
1008 // don't delete here, dropping the ref should be sufficient
1010 } // of top-level groups iteration
1012 FGRenderer* render = globals->get_renderer();
1013 // needed or we crash in multi-threaded OSG mode
1014 render->getViewer()->stopThreading();
1016 // order is important here since tile-manager shutdown needs to
1017 // access the scenery object
1018 globals->set_tile_mgr(NULL);
1019 globals->set_scenery(NULL);
1020 FGScenery::getPagerSingleton()->clearRequests();
1021 flightgear::CameraGroup::setDefault(NULL);
1023 // don't cancel the pager until after shutdown, since AIModels (and
1024 // potentially others) can queue delete requests on the pager.
1025 render->getViewer()->getDatabasePager()->cancel();
1026 render->getViewer()->getDatabasePager()->clear();
1028 osgDB::Registry::instance()->clearObjectCache();
1030 // preserve the event handler; re-creating it would entail fixing the
1032 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
1034 globals->set_renderer(NULL);
1035 globals->set_matlib(NULL);
1036 globals->set_chatter_queue(NULL);
1038 simgear::clearEffectCache();
1039 simgear::SGModelLib::resetPropertyRoot();
1041 simgear::GlobalParticleCallback::setSwitch(NULL);
1043 globals->resetPropertyRoot();
1044 // otherwise channels are duplicated
1045 globals->get_channel_options_list()->clear();
1047 fgInitConfig(0, NULL, true);
1048 fgInitGeneral(); // all of this?
1050 flightgear::Options::sharedInstance()->processOptions();
1052 // PRESERVED properties over-write state from options, intentionally
1053 if ( copyProperties(preserved, globals->get_props()) ) {
1054 SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1056 SG_LOG( SG_GENERAL, SG_INFO,
1057 "Some errors restoring preserved state (read-only props?)" );
1060 fgGetNode("/sim")->removeChild("aircraft-dir");
1061 fgInitAircraft(true);
1063 render = new FGRenderer;
1064 render->setEventHandler(eventHandler);
1065 eventHandler->reset();
1066 globals->set_renderer(render);
1068 render->setViewer(viewer.get());
1070 viewer->getDatabasePager()->setUpThreads(1, 1);
1072 // must do this before splashinit for Rembrandt
1073 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1074 render->splashinit();
1075 viewer->startThreading();
1077 fgOSResetProperties();
1079 // init some things manually
1080 // which do not follow the regular init pattern
1082 globals->get_event_mgr()->init();
1083 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1085 globals->set_matlib( new SGMaterialLib );
1087 // terra-sync needs the property tree root, pass it back in
1088 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1089 terra_sync->setRoot(globals->get_props());
1091 fgSetBool("/sim/signals/reinit", false);
1092 fgSetBool("/sim/freeze/master", false);
1093 fgSetBool("/sim/sceneryloaded",false);