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 <Aircraft/controls.hxx>
73 #include <Aircraft/replay.hxx>
74 #include <Aircraft/FlightHistory.hxx>
75 #include <Airports/runways.hxx>
76 #include <Airports/airport.hxx>
77 #include <Airports/dynamics.hxx>
79 #include <AIModel/AIManager.hxx>
81 #include <ATC/atc_mgr.hxx>
83 #include <Autopilot/route_mgr.hxx>
84 #include <Autopilot/autopilotgroup.hxx>
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
89 #include <Canvas/canvas_mgr.hxx>
90 #include <Canvas/gui_mgr.hxx>
91 #include <Canvas/FGCanvasSystemAdapter.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <GUI/MessageBox.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <Model/modelmgr.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/voice.hxx>
106 #include <Sound/soundmanager.hxx>
107 #include <Systems/system_mgr.hxx>
108 #include <Time/light.hxx>
109 #include <Time/TimeManager.hxx>
111 #include <Traffic/TrafficMgr.hxx>
112 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <FDM/fdm_shell.hxx>
114 #include <Environment/ephemeris.hxx>
115 #include <Environment/environment_mgr.hxx>
116 #include <Viewer/renderer.hxx>
117 #include <Viewer/viewmgr.hxx>
118 #include <Viewer/FGEventHandler.hxx>
119 #include <Navaids/NavDataCache.hxx>
120 #include <Instrumentation/HUD/HUD.hxx>
121 #include <Cockpit/cockpitDisplayManager.hxx>
122 #include <Network/HTTPClient.hxx>
123 #include <Network/fgcom.hxx>
125 #include <Viewer/CameraGroup.hxx>
127 #include "fg_init.hxx"
129 #include "fg_commands.hxx"
130 #include "fg_props.hxx"
131 #include "FGInterpolator.hxx"
132 #include "options.hxx"
133 #include "globals.hxx"
134 #include "logger.hxx"
136 #include "positioninit.hxx"
138 #include "AircraftDirVisitorBase.hxx"
141 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
144 //#define NEW_RESET 1
150 using namespace boost::algorithm;
152 extern osg::ref_ptr<osgViewer::Viewer> viewer;
154 // Return the current base package version
155 string fgBasePackageVersion() {
156 SGPath base_path( globals->get_fg_root() );
157 base_path.append("version");
158 if (!base_path.exists()) {
162 sg_gzifstream in( base_path.str() );
173 class FindAndCacheAircraft : public AircraftDirVistorBase
176 FindAndCacheAircraft(SGPropertyNode* autoSave)
178 _cache = autoSave->getNode("sim/startup/path-cache", true);
183 std::string aircraft = fgGetString( "/sim/aircraft", "");
184 if (aircraft.empty()) {
185 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
186 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
190 _searchAircraft = aircraft + "-set.xml";
191 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
192 if (!aircraftDir.empty()) {
193 // aircraft-dir was set, skip any searching at all, if it's valid
194 simgear::Dir acPath(aircraftDir);
195 SGPath setFile = acPath.file(_searchAircraft);
196 if (setFile.exists()) {
197 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
200 readProperties(setFile.str(), globals->get_props());
201 } catch ( const sg_exception &e ) {
202 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
203 flightgear::fatalMessageBox("Error reading aircraft",
204 "An error occured reading the requested aircraft (" + aircraft + ")",
205 e.getFormattedMessage());
211 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
212 "' not found in specified dir:" << aircraftDir);
213 flightgear::fatalMessageBox("Aircraft not found",
214 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
221 // prepare cache for re-scan
222 SGPropertyNode *n = _cache->getNode("fg-root", true);
223 n->setStringValue(globals->get_fg_root().c_str());
224 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
225 n = _cache->getNode("fg-aircraft", true);
226 n->setStringValue(getAircraftPaths().c_str());
227 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
228 _cache->removeChildren("aircraft");
230 visitAircraftPaths();
233 if (_foundPath.str().empty()) {
234 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
235 flightgear::fatalMessageBox("Aircraft not found",
236 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
241 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
242 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
243 if (!_foundPath.exists()) {
244 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
249 readProperties(_foundPath.str(), globals->get_props());
250 } catch ( const sg_exception &e ) {
251 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
252 flightgear::fatalMessageBox("Error reading aircraft",
253 "An error occured reading the requested aircraft (" + aircraft + ")",
254 e.getFormattedMessage());
262 SGPath getAircraftPaths() {
263 string_list pathList = globals->get_aircraft_paths();
264 SGPath aircraftPaths;
265 string_list::const_iterator it = pathList.begin();
266 if (it != pathList.end()) {
267 aircraftPaths.set(*it);
270 for (; it != pathList.end(); ++it) {
271 aircraftPaths.add(*it);
273 return aircraftPaths;
278 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
279 return false; // cache mismatch
282 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
283 return false; // cache mismatch
286 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
287 for (unsigned int i = 0; i < cache.size(); i++) {
288 const char *name = cache[i]->getStringValue("file", "");
289 if (!boost::equals(_searchAircraft, name, is_iequal())) {
293 SGPath xml(cache[i]->getStringValue("path", ""));
301 } // of aircraft in cache iteration
306 virtual VisitResult visit(const SGPath& p)
311 if (!_cache->getChild("aircraft", i++, false))
315 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
317 std::string fileName(p.file());
318 n = entry->getNode("file", true);
319 n->setStringValue(fileName);
320 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
322 n = entry->getNode("path", true);
323 n->setStringValue(p.dir());
324 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
326 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
331 return VISIT_CONTINUE;
334 std::string _searchAircraft;
336 SGPropertyNode* _cache;
340 static SGPath platformDefaultDataPath()
342 char *envp = ::getenv( "APPDATA" );
343 SGPath config( envp );
344 config.append( "flightgear.org" );
348 #elif defined(SG_MAC)
350 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
353 static SGPath platformDefaultDataPath()
355 return SGPath::home() / ".fgfs";
361 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
362 globals->set_fg_home(dataPath.c_str());
364 simgear::Dir fgHome(dataPath);
365 if (!fgHome.exists()) {
369 if (!fgHome.exists()) {
370 flightgear::fatalMessageBox("Problem setting up user data",
371 "Unable to create the user-data storage folder at: '"
372 + dataPath.str() + "'");
376 if (fgGetBool("/sim/fghome-readonly", false)) {
377 // user / config forced us into readonly mode, fine
378 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
382 // write our PID, and check writeability
383 SGPath pidPath(dataPath, "fgfs.pid");
384 if (pidPath.exists()) {
385 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
386 // set a marker property so terrasync/navcache don't try to write
387 // from secondary instances
388 fgSetBool("/sim/fghome-readonly", true);
394 #if defined(SG_WINDOWS)
395 size_t len = snprintf(buf, 16, "%d", _getpid());
397 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
398 FILE_SHARE_READ, /* sharing */
399 NULL, /* security attributes */
400 CREATE_NEW, /* error if already exists */
401 FILE_FLAG_DELETE_ON_CLOSE,
402 NULL /* template */);
404 result = (f != INVALID_HANDLE_VALUE);
407 WriteFile(f, buf, len, &written, NULL /* overlapped */);
410 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
412 ssize_t len = snprintf(buf, 16, "%d", getpid());
413 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
415 result = ::write(fd, buf, len) == len;
416 if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
421 fgSetBool("/sim/fghome-readonly", false);
424 flightgear::fatalMessageBox("File permissions problem",
425 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
426 "User-data at:" + dataPath.str());
431 // Read in configuration (file and command line)
432 int fgInitConfig ( int argc, char **argv, bool reinit )
434 SGPath dataPath = globals->get_fg_home();
436 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
437 if (!exportDir.exists()) {
438 exportDir.create(0755);
441 // Set /sim/fg-home and don't allow malign code to override it until
442 // Nasal security is set up. Use FG_HOME if necessary.
443 SGPropertyNode *home = fgGetNode("/sim", true);
444 home->removeChild("fg-home", 0);
445 home = home->getChild("fg-home", 0, true);
446 home->setStringValue(dataPath.c_str());
447 home->setAttribute(SGPropertyNode::WRITE, false);
450 flightgear::Options* options = flightgear::Options::sharedInstance();
452 options->init(argc, argv, dataPath);
455 bool loadDefaults = options->shouldLoadDefaultConfig();
457 // Read global preferences from $FG_ROOT/preferences.xml
458 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
459 fgLoadProps("preferences.xml", globals->get_props());
460 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
462 // do not load user settings when reset to default is requested, or if
463 // told to explicitly ignore
464 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
466 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
470 globals->loadUserSettings(dataPath);
473 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
474 }// of no-default-config selected
476 return flightgear::FG_OPTIONS_OK;
479 int fgInitAircraft(bool reinit)
481 // Scan user config files and command line for a specified aircraft.
483 flightgear::Options::sharedInstance()->initAircraft();
486 FindAndCacheAircraft f(globals->get_props());
487 if (!f.loadAircraft()) {
488 return flightgear::FG_OPTIONS_ERROR;
491 return flightgear::FG_OPTIONS_OK;
495 * Initialize vor/ndb/ils/fix list management and query systems (as
496 * well as simple airport db list)
497 * This is called multiple times in the case of a cache rebuild,
498 * to allow lengthy caching to take place in the background, without
499 * blocking the main/UI thread.
504 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
505 static bool doingRebuild = false;
506 if (doingRebuild || cache->isRebuildRequired()) {
508 bool finished = cache->rebuild();
510 // sleep to give the rebuild thread more time
511 SGTimeStamp::sleepForMSec(50);
516 FGTACANList *channellist = new FGTACANList;
517 globals->set_channellist( channellist );
519 SGPath path(globals->get_fg_root());
520 path.append( "Navaids/TACAN_freq.dat" );
521 flightgear::loadTacan(path, channellist);
526 // General house keeping initializations
527 bool fgInitGeneral() {
530 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
531 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
533 root = globals->get_fg_root();
534 if ( ! root.length() ) {
535 // No root path set? Then bail ...
536 SG_LOG( SG_GENERAL, SG_ALERT,
537 "Cannot continue without a path to the base package "
538 << "being defined." );
541 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
543 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
544 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
545 fgSetString("/sim/startup/browser-app", globals->get_browser());
547 simgear::Dir cwd(simgear::Dir::current());
548 SGPropertyNode *curr = fgGetNode("/sim", true);
549 curr->removeChild("fg-current", 0);
550 curr = curr->getChild("fg-current", 0, true);
551 curr->setStringValue(cwd.path().str());
552 curr->setAttribute(SGPropertyNode::WRITE, false);
554 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
555 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
559 // Write various configuraton values out to the logs
560 void fgOutputSettings()
562 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
563 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
565 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
566 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
567 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
569 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
570 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
573 // This is the top level init routine which calls all the other
574 // initialization routines. If you are adding a subsystem to flight
575 // gear, its initialization call should located in this routine.
576 // Returns non-zero if a problem encountered.
577 void fgCreateSubsystems(bool duringReset) {
579 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
580 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
582 ////////////////////////////////////////////////////////////////////
583 // Initialize the sound subsystem.
584 ////////////////////////////////////////////////////////////////////
585 // Sound manager uses an own subsystem group "SOUND" which is the last
586 // to be updated in every loop.
587 // Sound manager is updated last so it can use the CPU while the GPU
588 // is processing the scenery (doubled the frame-rate for me) -EMH-
589 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
591 ////////////////////////////////////////////////////////////////////
592 // Initialize the event manager subsystem.
593 ////////////////////////////////////////////////////////////////////
595 globals->get_event_mgr()->init();
596 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
598 ////////////////////////////////////////////////////////////////////
599 // Initialize the property interpolator subsystem. Put into the INIT
600 // group because the "nasal" subsystem may need it at GENERAL take-down.
601 ////////////////////////////////////////////////////////////////////
602 FGInterpolator* interp = new FGInterpolator;
603 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
604 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
605 SGPropertyNode::setInterpolationMgr(interp);
607 ////////////////////////////////////////////////////////////////////
608 // Add the FlightGear property utilities.
609 ////////////////////////////////////////////////////////////////////
610 globals->add_subsystem("properties", new FGProperties);
613 ////////////////////////////////////////////////////////////////////
614 // Add the performance monitoring system.
615 ////////////////////////////////////////////////////////////////////
616 globals->add_subsystem("performance-mon",
617 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
618 fgGetNode("/sim/performance-monitor", true)));
620 ////////////////////////////////////////////////////////////////////
621 // Initialize the material property subsystem.
622 ////////////////////////////////////////////////////////////////////
624 SGPath mpath( globals->get_fg_root() );
625 mpath.append( fgGetString("/sim/rendering/materials-file") );
626 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
627 globals->get_props()) ) {
628 throw sg_io_exception("Error loading materials file", mpath);
631 globals->add_subsystem( "http", new FGHTTPClient );
633 ////////////////////////////////////////////////////////////////////
634 // Initialize the scenery management subsystem.
635 ////////////////////////////////////////////////////////////////////
637 globals->get_scenery()->get_scene_graph()
638 ->addChild(simgear::Particles::getCommonRoot());
639 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
641 ////////////////////////////////////////////////////////////////////
642 // Initialize the flight model subsystem.
643 ////////////////////////////////////////////////////////////////////
645 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
647 ////////////////////////////////////////////////////////////////////
648 // Initialize the weather subsystem.
649 ////////////////////////////////////////////////////////////////////
651 // Initialize the weather modeling subsystem
652 globals->add_subsystem("environment", new FGEnvironmentMgr);
653 globals->add_subsystem("ephemeris", new Ephemeris);
655 ////////////////////////////////////////////////////////////////////
656 // Initialize the aircraft systems and instrumentation (before the
658 ////////////////////////////////////////////////////////////////////
660 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
661 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
662 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
663 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
665 ////////////////////////////////////////////////////////////////////
666 // Initialize the XML Autopilot subsystem.
667 ////////////////////////////////////////////////////////////////////
669 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
670 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
671 globals->add_subsystem( "route-manager", new FGRouteMgr );
673 ////////////////////////////////////////////////////////////////////
674 // Initialize the Input-Output subsystem
675 ////////////////////////////////////////////////////////////////////
676 globals->add_subsystem( "io", new FGIO );
678 ////////////////////////////////////////////////////////////////////
679 // Create and register the logger.
680 ////////////////////////////////////////////////////////////////////
682 globals->add_subsystem("logger", new FGLogger);
684 ////////////////////////////////////////////////////////////////////
685 // Create and register the XML GUI.
686 ////////////////////////////////////////////////////////////////////
688 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
690 //////////////////////////////////////////////////////////////////////
691 // Initialize the 2D cloud subsystem.
692 ////////////////////////////////////////////////////////////////////
693 fgGetBool("/sim/rendering/bump-mapping", false);
695 ////////////////////////////////////////////////////////////////////
696 // Initialize the canvas 2d drawing subsystem.
697 ////////////////////////////////////////////////////////////////////
698 simgear::canvas::Canvas::setSystemAdapter(
699 simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
701 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
702 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
704 ////////////////////////////////////////////////////////////////////
705 // Initialize the ATC subsystem
706 ////////////////////////////////////////////////////////////////////
707 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
709 ////////////////////////////////////////////////////////////////////
710 // Initialize multiplayer subsystem
711 ////////////////////////////////////////////////////////////////////
713 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
715 ////////////////////////////////////////////////////////////////////
716 // Initialise the AI Model Manager
717 ////////////////////////////////////////////////////////////////////
718 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
719 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
720 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
723 // It's probably a good idea to initialize the top level traffic manager
724 // After the AI and ATC systems have been initialized properly.
725 // AI Traffic manager
726 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
728 ////////////////////////////////////////////////////////////////////
729 // Add a new 2D panel.
730 ////////////////////////////////////////////////////////////////////
732 fgSetArchivable("/sim/panel/visibility");
733 fgSetArchivable("/sim/panel/x-offset");
734 fgSetArchivable("/sim/panel/y-offset");
735 fgSetArchivable("/sim/panel/jitter");
737 ////////////////////////////////////////////////////////////////////
738 // Initialize the controls subsystem.
739 ////////////////////////////////////////////////////////////////////
741 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
743 ////////////////////////////////////////////////////////////////////
744 // Initialize the input subsystem.
745 ////////////////////////////////////////////////////////////////////
747 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
750 ////////////////////////////////////////////////////////////////////
751 // Initialize the replay subsystem
752 ////////////////////////////////////////////////////////////////////
753 globals->add_subsystem("replay", new FGReplay);
754 globals->add_subsystem("history", new FGFlightHistory);
756 #ifdef ENABLE_AUDIO_SUPPORT
757 ////////////////////////////////////////////////////////////////////
758 // Initialize the sound-effects subsystem.
759 ////////////////////////////////////////////////////////////////////
760 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
764 ////////////////////////////////////////////////////////////////////
765 // Initialize the FGCom subsystem.
766 ////////////////////////////////////////////////////////////////////
767 globals->add_subsystem("fgcom", new FGCom);
770 ////////////////////////////////////////////////////////////////////
771 // Initialize the lighting subsystem.
772 ////////////////////////////////////////////////////////////////////
774 // ordering here is important : Nasal (via events), then models, then views
776 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
777 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
780 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
781 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
783 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
785 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
786 SGSubsystemMgr::DISPLAY);
789 void fgPostInitSubsystems()
794 ////////////////////////////////////////////////////////////////////////
795 // Initialize the Nasal interpreter.
796 // Do this last, so that the loaded scripts see initialized state
797 ////////////////////////////////////////////////////////////////////////
798 FGNasalSys* nasal = new FGNasalSys();
799 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
801 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
803 // Ensure IOrules and path validation are working properly by trying to
804 // access a folder/file which should never be accessible.
805 const char* no_access_path =
811 if( fgValidatePath(no_access_path, true) )
816 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
818 if( fgValidatePath(no_access_path, false) )
823 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
826 // initialize methods that depend on other subsystems.
828 globals->get_subsystem_mgr()->postinit();
829 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
831 ////////////////////////////////////////////////////////////////////////
832 // End of subsystem initialization.
833 ////////////////////////////////////////////////////////////////////
835 fgSetBool("/sim/crashed", false);
836 fgSetBool("/sim/initialized", true);
838 SG_LOG( SG_GENERAL, SG_INFO, endl);
840 // Save the initial state for future
842 globals->saveInitialState();
845 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
846 void fgReInitSubsystems()
853 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
855 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
857 // setup state to begin re-init
858 bool freeze = master_freeze->getBoolValue();
860 master_freeze->setBoolValue(true);
863 fgSetBool("/sim/signals/reinit", true);
864 fgSetBool("/sim/crashed", false);
866 // do actual re-init steps
867 globals->get_subsystem("flight")->unbind();
869 // reset control state, before restoring initial state; -set or config files
870 // may specify values for flaps, trim tabs, magnetos, etc
871 globals->get_controls()->reset_all();
873 globals->restoreInitialState();
875 // update our position based on current presets
876 // this will mark position as needed finalized which we'll do in the
878 flightgear::initPosition();
880 simgear::SGTerraSync* terraSync =
881 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
883 terraSync->reposition();
886 // Force reupdating the positions of the ai 3d models. They are used for
887 // initializing ground level for the FDM.
888 globals->get_subsystem("ai-model")->reinit();
890 // Initialize the FDM
891 globals->get_subsystem("flight")->reinit();
893 // reset replay buffers
894 globals->get_subsystem("replay")->reinit();
896 // reload offsets from config defaults
897 globals->get_viewmgr()->reinit();
899 // ugly: finalizePosition waits for METAR to arrive for the new airport.
900 // we don't re-init the environment manager here, since historically we did
901 // not, and doing so seems to have other issues. All that's needed is to
902 // schedule METAR fetch immediately, so it's available for finalizePosition.
903 // So we manually extract the METAR-fetching component inside the environment
904 // manager, and re-init that.
905 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
907 envMgr->get_subsystem("realwx")->reinit();
910 globals->get_subsystem("time")->reinit();
912 // need to bind FDMshell again, since we manually unbound it above...
913 globals->get_subsystem("flight")->bind();
915 // need to reset aircraft (systems/instruments) so they can adapt to current environment
916 globals->get_subsystem("systems")->reinit();
917 globals->get_subsystem("instrumentation")->reinit();
919 // setup state to end re-init
920 fgSetBool("/sim/signals/reinit", false);
922 master_freeze->setBoolValue(false);
924 fgSetBool("/sim/sceneryloaded",false);
928 // re-position is a simplified version of the traditional (legacy)
929 // reset procedure. We only need to poke systems which will be upset by
930 // a sudden change in aircraft position. Since this potentially includes
931 // Nasal, we trigger the 'reinit' signal.
932 void fgStartReposition()
934 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
935 SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
937 // ensure we are frozen
938 bool freeze = master_freeze->getBoolValue();
940 master_freeze->setBoolValue(true);
943 // set this signal so Nasal scripts can take action.
944 fgSetBool("/sim/signals/reinit", true);
945 fgSetBool("/sim/crashed", false);
947 globals->get_subsystem("flight")->unbind();
949 // update our position based on current presets
950 // this will mark position as needed finalized which we'll do in the
952 flightgear::initPosition();
954 simgear::SGTerraSync* terraSync =
955 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
957 terraSync->reposition();
960 // Force reupdating the positions of the ai 3d models. They are used for
961 // initializing ground level for the FDM.
962 //globals->get_subsystem("ai-model")->reinit();
964 // Initialize the FDM
965 globals->get_subsystem("flight")->reinit();
967 // reset replay buffers
968 globals->get_subsystem("replay")->reinit();
970 // ugly: finalizePosition waits for METAR to arrive for the new airport.
971 // we don't re-init the environment manager here, since historically we did
972 // not, and doing so seems to have other issues. All that's needed is to
973 // schedule METAR fetch immediately, so it's available for finalizePosition.
974 // So we manually extract the METAR-fetching component inside the environment
975 // manager, and re-init that.
976 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
978 envMgr->get_subsystem("realwx")->reinit();
981 // need to bind FDMshell again, since we manually unbound it above...
982 globals->get_subsystem("flight")->bind();
984 // need to reset aircraft (systems/instruments) so they can adapt to current environment
985 globals->get_subsystem("systems")->reinit();
986 globals->get_subsystem("instrumentation")->reinit();
988 // setup state to end re-init
989 fgSetBool("/sim/signals/reinit", false);
991 master_freeze->setBoolValue(false);
993 fgSetBool("/sim/sceneryloaded",false);
996 void fgStartNewReset()
998 SGPropertyNode_ptr preserved(new SGPropertyNode);
1000 if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
1001 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
1003 fgSetBool("/sim/signals/reinit", true);
1004 fgSetBool("/sim/freeze/master", true);
1006 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
1007 // Nasal is manually inited in fgPostInit, ensure it's already shutdown
1008 // before other subsystems, so Nasal listeners don't fire during shutdonw
1009 SGSubsystem* nasal = subsystemManger->get_subsystem("nasal");
1012 subsystemManger->remove("nasal");
1014 subsystemManger->shutdown();
1015 subsystemManger->unbind();
1017 // remove most subsystems, with a few exceptions.
1018 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
1019 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
1020 const string_list& names(grp->member_names());
1021 string_list::const_iterator it;
1022 for (it = names.begin(); it != names.end(); ++it) {
1023 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
1024 || (*it == "lighting"))
1030 subsystemManger->remove(it->c_str());
1031 } catch (std::exception& e) {
1032 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
1034 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
1037 // don't delete here, dropping the ref should be sufficient
1039 } // of top-level groups iteration
1041 // order is important here since tile-manager shutdown needs to
1042 // access the scenery object
1043 globals->set_tile_mgr(NULL);
1044 globals->set_scenery(NULL);
1045 flightgear::CameraGroup::setDefault(NULL);
1047 FGRenderer* render = globals->get_renderer();
1048 // don't cancel the pager until after shutdown, since AIModels (and
1049 // potentially others) can queue delete requests on the pager.
1050 render->getViewer()->getDatabasePager()->cancel();
1051 render->getViewer()->getDatabasePager()->clear();
1053 osgDB::Registry::instance()->clearObjectCache();
1055 // preserve the event handler; re-creating it would entail fixing the
1057 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
1059 globals->set_renderer(NULL);
1060 globals->set_matlib(NULL);
1061 globals->set_chatter_queue(NULL);
1063 simgear::clearEffectCache();
1064 simgear::SGModelLib::resetPropertyRoot();
1066 simgear::GlobalParticleCallback::setSwitch(NULL);
1068 globals->resetPropertyRoot();
1069 fgInitConfig(0, NULL, true);
1070 fgInitGeneral(); // all of this?
1072 if ( copyProperties(preserved, globals->get_props()) ) {
1073 SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1075 SG_LOG( SG_GENERAL, SG_INFO,
1076 "Some errors restoring preserved state (read-only props?)" );
1079 fgGetNode("/sim")->removeChild("aircraft-dir");
1080 fgInitAircraft(true);
1081 flightgear::Options::sharedInstance()->processOptions();
1083 render = new FGRenderer;
1084 render->setEventHandler(eventHandler);
1085 globals->set_renderer(render);
1087 render->setViewer(viewer.get());
1089 viewer->getDatabasePager()->setUpThreads(1, 1);
1091 // must do this before splashinit for Rembrandt
1092 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1093 render->splashinit();
1095 fgOSResetProperties();
1097 // init some things manually
1098 // which do not follow the regular init pattern
1100 globals->get_event_mgr()->init();
1101 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1103 globals->set_matlib( new SGMaterialLib );
1105 // terra-sync needs the property tree root, pass it back in
1106 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1107 terra_sync->setRoot(globals->get_props());
1109 fgSetBool("/sim/signals/reinit", false);
1110 fgSetBool("/sim/freeze/master", false);
1111 fgSetBool("/sim/sceneryloaded",false);