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/constants.h>
54 #include <simgear/debug/logstream.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/event_mgr.hxx>
57 #include <simgear/structure/SGPerfMon.hxx>
58 #include <simgear/misc/sg_path.hxx>
59 #include <simgear/misc/sg_dir.hxx>
60 #include <simgear/misc/sgstream.hxx>
61 #include <simgear/misc/strutils.hxx>
62 #include <simgear/props/props_io.hxx>
63 #include <simgear/scene/tsync/terrasync.hxx>
65 #include <simgear/scene/model/modellib.hxx>
66 #include <simgear/scene/material/matlib.hxx>
67 #include <simgear/scene/model/particles.hxx>
68 #include <simgear/scene/tsync/terrasync.hxx>
70 #include <Aircraft/controls.hxx>
71 #include <Aircraft/replay.hxx>
72 #include <Aircraft/FlightHistory.hxx>
73 #include <Airports/runways.hxx>
74 #include <Airports/airport.hxx>
75 #include <Airports/dynamics.hxx>
77 #include <AIModel/AIManager.hxx>
79 #include <ATCDCL/ATISmgr.hxx>
80 #include <ATC/atc_mgr.hxx>
82 #include <Autopilot/route_mgr.hxx>
83 #include <Autopilot/autopilotgroup.hxx>
85 #include <Cockpit/panel.hxx>
86 #include <Cockpit/panel_io.hxx>
88 #include <Canvas/canvas_mgr.hxx>
89 #include <Canvas/gui_mgr.hxx>
90 #include <GUI/new_gui.hxx>
91 #include <GUI/MessageBox.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <Model/modelmgr.hxx>
96 #include <AIModel/submodel.hxx>
97 #include <AIModel/AIManager.hxx>
98 #include <Navaids/navdb.hxx>
99 #include <Navaids/navlist.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/tilemgr.hxx>
102 #include <Scripting/NasalSys.hxx>
103 #include <Sound/voice.hxx>
104 #include <Sound/soundmanager.hxx>
105 #include <Systems/system_mgr.hxx>
106 #include <Time/light.hxx>
107 #include <Time/TimeManager.hxx>
109 #include <Traffic/TrafficMgr.hxx>
110 #include <MultiPlayer/multiplaymgr.hxx>
111 #include <FDM/fdm_shell.hxx>
112 #include <Environment/ephemeris.hxx>
113 #include <Environment/environment_mgr.hxx>
114 #include <Viewer/renderer.hxx>
115 #include <Viewer/viewmgr.hxx>
116 #include <Viewer/FGEventHandler.hxx>
117 #include <Navaids/NavDataCache.hxx>
118 #include <Instrumentation/HUD/HUD.hxx>
119 #include <Cockpit/cockpitDisplayManager.hxx>
120 #include <Network/HTTPClient.hxx>
121 #include <Network/fgcom.hxx>
123 #include <Viewer/CameraGroup.hxx>
125 #include "fg_init.hxx"
127 #include "fg_commands.hxx"
128 #include "fg_props.hxx"
129 #include "FGInterpolator.hxx"
130 #include "options.hxx"
131 #include "globals.hxx"
132 #include "logger.hxx"
134 #include "positioninit.hxx"
136 #include "AircraftDirVisitorBase.hxx"
139 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
142 //#define NEW_RESET 1
148 using namespace boost::algorithm;
150 extern osg::ref_ptr<osgViewer::Viewer> viewer;
152 // Return the current base package version
153 string fgBasePackageVersion() {
154 SGPath base_path( globals->get_fg_root() );
155 base_path.append("version");
156 if (!base_path.exists()) {
160 sg_gzifstream in( base_path.str() );
171 class FindAndCacheAircraft : public AircraftDirVistorBase
174 FindAndCacheAircraft(SGPropertyNode* autoSave)
176 _cache = autoSave->getNode("sim/startup/path-cache", true);
181 std::string aircraft = fgGetString( "/sim/aircraft", "");
182 if (aircraft.empty()) {
183 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
184 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
188 _searchAircraft = aircraft + "-set.xml";
189 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
190 if (!aircraftDir.empty()) {
191 // aircraft-dir was set, skip any searching at all, if it's valid
192 simgear::Dir acPath(aircraftDir);
193 SGPath setFile = acPath.file(_searchAircraft);
194 if (setFile.exists()) {
195 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
198 readProperties(setFile.str(), globals->get_props());
199 } catch ( const sg_exception &e ) {
200 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
201 flightgear::fatalMessageBox("Error reading aircraft",
202 "An error occured reading the requested aircraft (" + aircraft + ")",
203 e.getFormattedMessage());
209 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
210 "' not found in specified dir:" << aircraftDir);
211 flightgear::fatalMessageBox("Aircraft not found",
212 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
219 // prepare cache for re-scan
220 SGPropertyNode *n = _cache->getNode("fg-root", true);
221 n->setStringValue(globals->get_fg_root().c_str());
222 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
223 n = _cache->getNode("fg-aircraft", true);
224 n->setStringValue(getAircraftPaths().c_str());
225 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
226 _cache->removeChildren("aircraft");
228 visitAircraftPaths();
231 if (_foundPath.str().empty()) {
232 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
233 flightgear::fatalMessageBox("Aircraft not found",
234 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
239 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
240 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
241 if (!_foundPath.exists()) {
242 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
247 readProperties(_foundPath.str(), globals->get_props());
248 } catch ( const sg_exception &e ) {
249 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
250 flightgear::fatalMessageBox("Error reading aircraft",
251 "An error occured reading the requested aircraft (" + aircraft + ")",
252 e.getFormattedMessage());
260 SGPath getAircraftPaths() {
261 string_list pathList = globals->get_aircraft_paths();
262 SGPath aircraftPaths;
263 string_list::const_iterator it = pathList.begin();
264 if (it != pathList.end()) {
265 aircraftPaths.set(*it);
268 for (; it != pathList.end(); ++it) {
269 aircraftPaths.add(*it);
271 return aircraftPaths;
276 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
277 return false; // cache mismatch
280 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
281 return false; // cache mismatch
284 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
285 for (unsigned int i = 0; i < cache.size(); i++) {
286 const char *name = cache[i]->getStringValue("file", "");
287 if (!boost::equals(_searchAircraft, name, is_iequal())) {
291 SGPath xml(cache[i]->getStringValue("path", ""));
299 } // of aircraft in cache iteration
304 virtual VisitResult visit(const SGPath& p)
309 if (!_cache->getChild("aircraft", i++, false))
313 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
315 std::string fileName(p.file());
316 n = entry->getNode("file", true);
317 n->setStringValue(fileName);
318 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
320 n = entry->getNode("path", true);
321 n->setStringValue(p.dir());
322 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
324 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
329 return VISIT_CONTINUE;
332 std::string _searchAircraft;
334 SGPropertyNode* _cache;
338 static SGPath platformDefaultDataPath()
340 char *envp = ::getenv( "APPDATA" );
341 SGPath config( envp );
342 config.append( "flightgear.org" );
346 #elif defined(SG_MAC)
348 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
351 static SGPath platformDefaultDataPath()
353 return SGPath::home() / ".fgfs";
359 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
360 globals->set_fg_home(dataPath.c_str());
362 simgear::Dir fgHome(dataPath);
363 if (!fgHome.exists()) {
367 if (!fgHome.exists()) {
368 flightgear::fatalMessageBox("Problem setting up user data",
369 "Unable to create the user-data storage folder at: '"
370 + dataPath.str() + "'");
374 if (fgGetBool("/sim/fghome-readonly", false)) {
375 // user / config forced us into readonly mode, fine
376 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
380 // write our PID, and check writeability
381 SGPath pidPath(dataPath, "fgfs.pid");
382 if (pidPath.exists()) {
383 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
384 // set a marker property so terrasync/navcache don't try to write
385 // from secondary instances
386 fgSetBool("/sim/fghome-readonly", true);
392 #if defined(SG_WINDOWS)
393 size_t len = snprintf(buf, 16, "%d", _getpid());
395 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
396 FILE_SHARE_READ, /* sharing */
397 NULL, /* security attributes */
398 CREATE_NEW, /* error if already exists */
399 FILE_FLAG_DELETE_ON_CLOSE,
400 NULL /* template */);
402 result = (f != INVALID_HANDLE_VALUE);
405 WriteFile(f, buf, len, &written, NULL /* overlapped */);
408 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
410 size_t len = snprintf(buf, 16, "%d", getpid());
411 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
413 ::write(fd, buf, len);
414 ::unlink(pidPath.c_str()); // delete file when app quits
418 fgSetBool("/sim/fghome-readonly", false);
421 flightgear::fatalMessageBox("File permissions problem",
422 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
423 "User-data at:" + dataPath.str());
428 // Read in configuration (file and command line)
429 int fgInitConfig ( int argc, char **argv, bool reinit )
431 SGPath dataPath = globals->get_fg_home();
433 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
434 if (!exportDir.exists()) {
435 exportDir.create(0777);
438 // Set /sim/fg-home and don't allow malign code to override it until
439 // Nasal security is set up. Use FG_HOME if necessary.
440 SGPropertyNode *home = fgGetNode("/sim", true);
441 home->removeChild("fg-home", 0, false);
442 home = home->getChild("fg-home", 0, true);
443 home->setStringValue(dataPath.c_str());
444 home->setAttribute(SGPropertyNode::WRITE, false);
447 flightgear::Options* options = flightgear::Options::sharedInstance();
449 options->init(argc, argv, dataPath);
452 bool loadDefaults = options->shouldLoadDefaultConfig();
454 // Read global preferences from $FG_ROOT/preferences.xml
455 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
456 fgLoadProps("preferences.xml", globals->get_props());
457 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
459 // do not load user settings when reset to default is requested, or if
460 // told to explicitly ignore
461 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
463 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
467 globals->loadUserSettings(dataPath);
470 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
471 }// of no-default-config selected
473 return flightgear::FG_OPTIONS_OK;
476 int fgInitAircraft(bool reinit)
478 // Scan user config files and command line for a specified aircraft.
480 flightgear::Options::sharedInstance()->initAircraft();
483 FindAndCacheAircraft f(globals->get_props());
484 if (!f.loadAircraft()) {
485 return flightgear::FG_OPTIONS_ERROR;
488 return flightgear::FG_OPTIONS_OK;
492 * Initialize vor/ndb/ils/fix list management and query systems (as
493 * well as simple airport db list)
494 * This is called multiple times in the case of a cache rebuild,
495 * to allow lengthy caching to take place in the background, without
496 * blocking the main/UI thread.
501 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
502 static bool doingRebuild = false;
503 if (doingRebuild || cache->isRebuildRequired()) {
505 bool finished = cache->rebuild();
507 // sleep to give the rebuild thread more time
508 SGTimeStamp::sleepForMSec(50);
513 FGTACANList *channellist = new FGTACANList;
514 globals->set_channellist( channellist );
516 SGPath path(globals->get_fg_root());
517 path.append( "Navaids/TACAN_freq.dat" );
518 flightgear::loadTacan(path, channellist);
523 // General house keeping initializations
524 bool fgInitGeneral() {
527 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
528 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
530 root = globals->get_fg_root();
531 if ( ! root.length() ) {
532 // No root path set? Then bail ...
533 SG_LOG( SG_GENERAL, SG_ALERT,
534 "Cannot continue without a path to the base package "
535 << "being defined." );
538 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
540 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
541 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
542 fgSetString("/sim/startup/browser-app", globals->get_browser());
544 simgear::Dir cwd(simgear::Dir::current());
545 SGPropertyNode *curr = fgGetNode("/sim", true);
546 curr->removeChild("fg-current", 0, false);
547 curr = curr->getChild("fg-current", 0, true);
548 curr->setStringValue(cwd.path().str());
549 curr->setAttribute(SGPropertyNode::WRITE, false);
551 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
552 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
556 // Write various configuraton values out to the logs
557 void fgOutputSettings()
559 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
560 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
562 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
563 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
564 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
566 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
567 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
570 // This is the top level init routine which calls all the other
571 // initialization routines. If you are adding a subsystem to flight
572 // gear, its initialization call should located in this routine.
573 // Returns non-zero if a problem encountered.
574 void fgCreateSubsystems(bool duringReset) {
576 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
577 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
579 ////////////////////////////////////////////////////////////////////
580 // Initialize the sound subsystem.
581 ////////////////////////////////////////////////////////////////////
582 // Sound manager uses an own subsystem group "SOUND" which is the last
583 // to be updated in every loop.
584 // Sound manager is updated last so it can use the CPU while the GPU
585 // is processing the scenery (doubled the frame-rate for me) -EMH-
586 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
588 ////////////////////////////////////////////////////////////////////
589 // Initialize the event manager subsystem.
590 ////////////////////////////////////////////////////////////////////
592 globals->get_event_mgr()->init();
593 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
595 ////////////////////////////////////////////////////////////////////
596 // Initialize the property interpolator subsystem. Put into the INIT
597 // group because the "nasal" subsystem may need it at GENERAL take-down.
598 ////////////////////////////////////////////////////////////////////
599 FGInterpolator* interp = new FGInterpolator;
600 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
601 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
602 SGPropertyNode::setInterpolationMgr(interp);
604 ////////////////////////////////////////////////////////////////////
605 // Add the FlightGear property utilities.
606 ////////////////////////////////////////////////////////////////////
607 globals->add_subsystem("properties", new FGProperties);
610 ////////////////////////////////////////////////////////////////////
611 // Add the performance monitoring system.
612 ////////////////////////////////////////////////////////////////////
613 globals->add_subsystem("performance-mon",
614 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
615 fgGetNode("/sim/performance-monitor", true)));
617 ////////////////////////////////////////////////////////////////////
618 // Initialize the material property subsystem.
619 ////////////////////////////////////////////////////////////////////
621 SGPath mpath( globals->get_fg_root() );
622 mpath.append( fgGetString("/sim/rendering/materials-file") );
623 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
624 globals->get_props()) ) {
625 throw sg_io_exception("Error loading materials file", mpath);
628 globals->add_subsystem( "http", new FGHTTPClient );
630 ////////////////////////////////////////////////////////////////////
631 // Initialize the scenery management subsystem.
632 ////////////////////////////////////////////////////////////////////
634 globals->get_scenery()->get_scene_graph()
635 ->addChild(simgear::Particles::getCommonRoot());
636 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
638 ////////////////////////////////////////////////////////////////////
639 // Initialize the flight model subsystem.
640 ////////////////////////////////////////////////////////////////////
642 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
644 ////////////////////////////////////////////////////////////////////
645 // Initialize the weather subsystem.
646 ////////////////////////////////////////////////////////////////////
648 // Initialize the weather modeling subsystem
649 globals->add_subsystem("environment", new FGEnvironmentMgr);
650 globals->add_subsystem("ephemeris", new Ephemeris);
652 ////////////////////////////////////////////////////////////////////
653 // Initialize the aircraft systems and instrumentation (before the
655 ////////////////////////////////////////////////////////////////////
657 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
658 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
659 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
660 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
662 ////////////////////////////////////////////////////////////////////
663 // Initialize the XML Autopilot subsystem.
664 ////////////////////////////////////////////////////////////////////
666 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
667 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
668 globals->add_subsystem( "route-manager", new FGRouteMgr );
670 ////////////////////////////////////////////////////////////////////
671 // Initialize the Input-Output subsystem
672 ////////////////////////////////////////////////////////////////////
673 globals->add_subsystem( "io", new FGIO );
675 ////////////////////////////////////////////////////////////////////
676 // Create and register the logger.
677 ////////////////////////////////////////////////////////////////////
679 globals->add_subsystem("logger", new FGLogger);
681 ////////////////////////////////////////////////////////////////////
682 // Create and register the XML GUI.
683 ////////////////////////////////////////////////////////////////////
685 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
687 //////////////////////////////////////////////////////////////////////
688 // Initialize the 2D cloud subsystem.
689 ////////////////////////////////////////////////////////////////////
690 fgGetBool("/sim/rendering/bump-mapping", false);
692 ////////////////////////////////////////////////////////////////////
693 // Initialize the canvas 2d drawing subsystem.
694 ////////////////////////////////////////////////////////////////////
695 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
696 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
698 ////////////////////////////////////////////////////////////////////
699 // Initialise the ATIS Manager
700 // Note that this is old stuff, but is necessary for the
701 // current ATIS implementation. Therefore, leave it in here
702 // until the ATIS system is ported over to make use of the ATIS
703 // sub system infrastructure.
704 ////////////////////////////////////////////////////////////////////
706 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
708 ////////////////////////////////////////////////////////////////////
709 // Initialize the ATC subsystem
710 ////////////////////////////////////////////////////////////////////
711 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
713 ////////////////////////////////////////////////////////////////////
714 // Initialize multiplayer subsystem
715 ////////////////////////////////////////////////////////////////////
717 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
719 ////////////////////////////////////////////////////////////////////
720 // Initialise the AI Model Manager
721 ////////////////////////////////////////////////////////////////////
722 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
723 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
724 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
727 // It's probably a good idea to initialize the top level traffic manager
728 // After the AI and ATC systems have been initialized properly.
729 // AI Traffic manager
730 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
732 ////////////////////////////////////////////////////////////////////
733 // Add a new 2D panel.
734 ////////////////////////////////////////////////////////////////////
736 fgSetArchivable("/sim/panel/visibility");
737 fgSetArchivable("/sim/panel/x-offset");
738 fgSetArchivable("/sim/panel/y-offset");
739 fgSetArchivable("/sim/panel/jitter");
741 ////////////////////////////////////////////////////////////////////
742 // Initialize the controls subsystem.
743 ////////////////////////////////////////////////////////////////////
745 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
747 ////////////////////////////////////////////////////////////////////
748 // Initialize the input subsystem.
749 ////////////////////////////////////////////////////////////////////
751 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
754 ////////////////////////////////////////////////////////////////////
755 // Initialize the replay subsystem
756 ////////////////////////////////////////////////////////////////////
757 globals->add_subsystem("replay", new FGReplay);
758 globals->add_subsystem("history", new FGFlightHistory);
760 #ifdef ENABLE_AUDIO_SUPPORT
761 ////////////////////////////////////////////////////////////////////
762 // Initialize the sound-effects subsystem.
763 ////////////////////////////////////////////////////////////////////
764 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
768 ////////////////////////////////////////////////////////////////////
769 // Initialize the FGCom subsystem.
770 ////////////////////////////////////////////////////////////////////
771 globals->add_subsystem("fgcom", new FGCom);
774 ////////////////////////////////////////////////////////////////////
775 // Initialize the lighting subsystem.
776 ////////////////////////////////////////////////////////////////////
778 // ordering here is important : Nasal (via events), then models, then views
780 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
781 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
784 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
785 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
787 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
789 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
790 SGSubsystemMgr::DISPLAY);
793 void fgPostInitSubsystems()
798 ////////////////////////////////////////////////////////////////////////
799 // Initialize the Nasal interpreter.
800 // Do this last, so that the loaded scripts see initialized state
801 ////////////////////////////////////////////////////////////////////////
802 FGNasalSys* nasal = new FGNasalSys();
803 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
805 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
807 // Ensure IOrules and path validation are working properly by trying to
808 // access a folder/file which should never be accessible.
809 const char* no_access_path =
815 if( fgValidatePath(no_access_path, true) )
820 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
822 if( fgValidatePath(no_access_path, false) )
827 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
830 // initialize methods that depend on other subsystems.
832 globals->get_subsystem_mgr()->postinit();
833 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
835 ////////////////////////////////////////////////////////////////////////
836 // End of subsystem initialization.
837 ////////////////////////////////////////////////////////////////////
839 fgSetBool("/sim/crashed", false);
840 fgSetBool("/sim/initialized", true);
842 SG_LOG( SG_GENERAL, SG_INFO, endl);
844 // Save the initial state for future
846 globals->saveInitialState();
849 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
850 void fgReInitSubsystems()
857 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
859 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
861 // setup state to begin re-init
862 bool freeze = master_freeze->getBoolValue();
864 master_freeze->setBoolValue(true);
867 fgSetBool("/sim/signals/reinit", true);
868 fgSetBool("/sim/crashed", false);
870 // do actual re-init steps
871 globals->get_subsystem("flight")->unbind();
873 // reset control state, before restoring initial state; -set or config files
874 // may specify values for flaps, trim tabs, magnetos, etc
875 globals->get_controls()->reset_all();
877 globals->restoreInitialState();
879 // update our position based on current presets
880 // this will mark position as needed finalized which we'll do in the
882 flightgear::initPosition();
884 simgear::SGTerraSync* terraSync =
885 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
887 terraSync->reposition();
890 // Force reupdating the positions of the ai 3d models. They are used for
891 // initializing ground level for the FDM.
892 globals->get_subsystem("ai-model")->reinit();
894 // Initialize the FDM
895 globals->get_subsystem("flight")->reinit();
897 // reset replay buffers
898 globals->get_subsystem("replay")->reinit();
900 // reload offsets from config defaults
901 globals->get_viewmgr()->reinit();
903 // ugly: finalizePosition waits for METAR to arrive for the new airport.
904 // we don't re-init the environment manager here, since historically we did
905 // not, and doing so seems to have other issues. All that's needed is to
906 // schedule METAR fetch immediately, so it's available for finalizePosition.
907 // So we manually extract the METAR-fetching component inside the environment
908 // manager, and re-init that.
909 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
911 envMgr->get_subsystem("realwx")->reinit();
914 globals->get_subsystem("time")->reinit();
916 // need to bind FDMshell again, since we manually unbound it above...
917 globals->get_subsystem("flight")->bind();
919 // need to reset aircraft (systems/instruments) so they can adapt to current environment
920 globals->get_subsystem("systems")->reinit();
921 globals->get_subsystem("instrumentation")->reinit();
923 globals->get_subsystem("ATIS")->reinit();
925 // setup state to end re-init
926 fgSetBool("/sim/signals/reinit", false);
928 master_freeze->setBoolValue(false);
930 fgSetBool("/sim/sceneryloaded",false);
933 void fgStartNewReset()
935 globals->saveInitialState();
937 fgSetBool("/sim/signals/reinit", true);
938 fgSetBool("/sim/freeze/master", true);
940 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
941 subsystemManger->shutdown();
942 subsystemManger->unbind();
944 // remove them all (with some exceptions?)
945 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
946 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
947 const string_list& names(grp->member_names());
948 string_list::const_iterator it;
949 for (it = names.begin(); it != names.end(); ++it) {
950 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
951 || (*it == "lighting"))
957 subsystemManger->remove(it->c_str());
958 } catch (std::exception& e) {
959 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
961 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
964 // don't delete here, dropping the ref should be sufficient
966 } // of top-level groups iteration
968 // order is important here since tile-manager shutdown needs to
969 // access the scenery object
970 globals->set_tile_mgr(NULL);
971 globals->set_scenery(NULL);
972 flightgear::CameraGroup::setDefault(NULL);
974 FGRenderer* render = globals->get_renderer();
975 // don't cancel the pager until after shutdown, since AIModels (and
976 // potentially others) can queue delete requests on the pager.
977 render->getViewer()->getDatabasePager()->cancel();
979 // preserve the event handler; re-creating it would entail fixing the
981 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
983 globals->set_renderer(NULL);
984 globals->set_matlib(NULL);
985 simgear::SGModelLib::resetPropertyRoot();
987 globals->resetPropertyRoot();
988 globals->restoreInitialState();
990 fgInitConfig(0, NULL, true);
991 fgInitGeneral(); // all of this?
993 fgGetNode("/sim")->removeChild("aircraft-dir");
994 fgInitAircraft(true);
995 flightgear::Options::sharedInstance()->processOptions();
997 render = new FGRenderer;
998 render->setEventHandler(eventHandler);
999 globals->set_renderer(render);
1001 render->setViewer(viewer.get());
1002 viewer->getDatabasePager()->setUpThreads(1, 1);
1003 render->splashinit();
1005 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1007 fgOSResetProperties();
1010 // init some things manually
1011 // which do not follow the regular init pattern
1013 globals->get_event_mgr()->init();
1014 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1016 globals->set_matlib( new SGMaterialLib );
1018 // terra-sync needs the property tree root, pass it back in
1019 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1020 terra_sync->setRoot(globals->get_props());
1022 fgSetBool("/sim/signals/reinit", false);
1023 fgSetBool("/sim/freeze/master", false);
1024 fgSetBool("/sim/sceneryloaded",false);