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>
74 #include <Aircraft/controls.hxx>
75 #include <Aircraft/replay.hxx>
76 #include <Aircraft/FlightHistory.hxx>
77 #include <Airports/runways.hxx>
78 #include <Airports/airport.hxx>
79 #include <Airports/dynamics.hxx>
81 #include <AIModel/AIManager.hxx>
83 #include <ATC/atc_mgr.hxx>
85 #include <Autopilot/route_mgr.hxx>
86 #include <Autopilot/autopilotgroup.hxx>
88 #include <Cockpit/panel.hxx>
89 #include <Cockpit/panel_io.hxx>
91 #include <Canvas/canvas_mgr.hxx>
92 #include <Canvas/gui_mgr.hxx>
93 #include <Canvas/FGCanvasSystemAdapter.hxx>
94 #include <GUI/new_gui.hxx>
95 #include <GUI/MessageBox.hxx>
96 #include <Input/input.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <Model/modelmgr.hxx>
100 #include <AIModel/submodel.hxx>
101 #include <AIModel/AIManager.hxx>
102 #include <Navaids/navdb.hxx>
103 #include <Navaids/navlist.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/SceneryPager.hxx>
106 #include <Scenery/tilemgr.hxx>
107 #include <Scripting/NasalSys.hxx>
108 #include <Sound/voice.hxx>
109 #include <Sound/soundmanager.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/TimeManager.hxx>
114 #include <Traffic/TrafficMgr.hxx>
115 #include <MultiPlayer/multiplaymgr.hxx>
116 #include <FDM/fdm_shell.hxx>
117 #include <Environment/ephemeris.hxx>
118 #include <Environment/environment_mgr.hxx>
119 #include <Viewer/renderer.hxx>
120 #include <Viewer/viewmgr.hxx>
121 #include <Viewer/FGEventHandler.hxx>
122 #include <Navaids/NavDataCache.hxx>
123 #include <Instrumentation/HUD/HUD.hxx>
124 #include <Cockpit/cockpitDisplayManager.hxx>
125 #include <Network/HTTPClient.hxx>
126 #include <Network/fgcom.hxx>
127 #include <Network/http/httpd.hxx>
128 #include <Include/version.h>
130 #include <Viewer/CameraGroup.hxx>
132 #include "fg_init.hxx"
134 #include "fg_commands.hxx"
135 #include "fg_props.hxx"
136 #include "FGInterpolator.hxx"
137 #include "options.hxx"
138 #include "globals.hxx"
139 #include "logger.hxx"
141 #include "positioninit.hxx"
143 #include "AircraftDirVisitorBase.hxx"
146 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
156 using namespace boost::algorithm;
157 using namespace simgear::pkg;
159 extern osg::ref_ptr<osgViewer::Viewer> viewer;
161 // Return the current base package version
162 string fgBasePackageVersion() {
163 SGPath base_path( globals->get_fg_root() );
164 base_path.append("version");
165 if (!base_path.exists()) {
169 sg_gzifstream in( base_path.str() );
180 class FindAndCacheAircraft : public AircraftDirVistorBase
183 FindAndCacheAircraft(SGPropertyNode* autoSave)
185 _cache = autoSave->getNode("sim/startup/path-cache", true);
190 std::string aircraft = fgGetString( "/sim/aircraft", "");
191 if (aircraft.empty()) {
192 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
193 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
197 _searchAircraft = aircraft + "-set.xml";
198 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
199 if (!aircraftDir.empty()) {
200 // aircraft-dir was set, skip any searching at all, if it's valid
201 simgear::Dir acPath(aircraftDir);
202 SGPath setFile = acPath.file(_searchAircraft);
203 if (setFile.exists()) {
204 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
207 readProperties(setFile.str(), globals->get_props());
208 } catch ( const sg_exception &e ) {
209 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
210 flightgear::fatalMessageBox("Error reading aircraft",
211 "An error occured reading the requested aircraft (" + aircraft + ")",
212 e.getFormattedMessage());
218 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
219 "' not found in specified dir:" << aircraftDir);
220 flightgear::fatalMessageBox("Aircraft not found",
221 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
228 // prepare cache for re-scan
229 SGPropertyNode *n = _cache->getNode("fg-root", true);
230 n->setStringValue(globals->get_fg_root().c_str());
231 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
232 n = _cache->getNode("fg-aircraft", true);
233 n->setStringValue(getAircraftPaths().c_str());
234 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
235 _cache->removeChildren("aircraft");
237 visitAircraftPaths();
240 if (_foundPath.str().empty()) {
241 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
242 flightgear::fatalMessageBox("Aircraft not found",
243 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
248 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
249 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
250 if (!_foundPath.exists()) {
251 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
256 readProperties(_foundPath.str(), globals->get_props());
257 } catch ( const sg_exception &e ) {
258 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
259 flightgear::fatalMessageBox("Error reading aircraft",
260 "An error occured reading the requested aircraft (" + aircraft + ")",
261 e.getFormattedMessage());
269 SGPath getAircraftPaths() {
270 string_list pathList = globals->get_aircraft_paths();
271 SGPath aircraftPaths;
272 string_list::const_iterator it = pathList.begin();
273 if (it != pathList.end()) {
274 aircraftPaths.set(*it);
277 for (; it != pathList.end(); ++it) {
278 aircraftPaths.add(*it);
280 return aircraftPaths;
285 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
286 return false; // cache mismatch
289 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
290 return false; // cache mismatch
293 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
294 for (unsigned int i = 0; i < cache.size(); i++) {
295 const char *name = cache[i]->getStringValue("file", "");
296 if (!boost::equals(_searchAircraft, name, is_iequal())) {
300 SGPath xml(cache[i]->getStringValue("path", ""));
308 } // of aircraft in cache iteration
313 virtual VisitResult visit(const SGPath& p)
318 if (!_cache->getChild("aircraft", i++, false))
322 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
324 std::string fileName(p.file());
325 n = entry->getNode("file", true);
326 n->setStringValue(fileName);
327 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
329 n = entry->getNode("path", true);
330 n->setStringValue(p.dir());
331 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
333 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
338 return VISIT_CONTINUE;
341 std::string _searchAircraft;
343 SGPropertyNode* _cache;
347 static SGPath platformDefaultDataPath()
349 char *envp = ::getenv( "APPDATA" );
350 SGPath config( envp );
351 config.append( "flightgear.org" );
355 #elif defined(SG_MAC)
357 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
360 static SGPath platformDefaultDataPath()
362 return SGPath::home() / ".fgfs";
368 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
369 globals->set_fg_home(dataPath.c_str());
371 simgear::Dir fgHome(dataPath);
372 if (!fgHome.exists()) {
376 if (!fgHome.exists()) {
377 flightgear::fatalMessageBox("Problem setting up user data",
378 "Unable to create the user-data storage folder at: '"
379 + dataPath.str() + "'");
383 if (fgGetBool("/sim/fghome-readonly", false)) {
384 // user / config forced us into readonly mode, fine
385 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
389 // write our PID, and check writeability
390 SGPath pidPath(dataPath, "fgfs.pid");
391 if (pidPath.exists()) {
392 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
393 // set a marker property so terrasync/navcache don't try to write
394 // from secondary instances
395 fgSetBool("/sim/fghome-readonly", true);
401 #if defined(SG_WINDOWS)
402 size_t len = snprintf(buf, 16, "%d", _getpid());
404 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
405 FILE_SHARE_READ, /* sharing */
406 NULL, /* security attributes */
407 CREATE_NEW, /* error if already exists */
408 FILE_FLAG_DELETE_ON_CLOSE,
409 NULL /* template */);
411 result = (f != INVALID_HANDLE_VALUE);
414 WriteFile(f, buf, len, &written, NULL /* overlapped */);
417 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
419 ssize_t len = snprintf(buf, 16, "%d", getpid());
420 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
422 result = ::write(fd, buf, len) == len;
423 if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
428 fgSetBool("/sim/fghome-readonly", false);
431 flightgear::fatalMessageBox("File permissions problem",
432 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
433 "User-data at:" + dataPath.str());
438 // Read in configuration (file and command line)
439 int fgInitConfig ( int argc, char **argv, bool reinit )
441 SGPath dataPath = globals->get_fg_home();
443 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
444 if (!exportDir.exists()) {
445 exportDir.create(0755);
448 // Set /sim/fg-home and don't allow malign code to override it until
449 // Nasal security is set up. Use FG_HOME if necessary.
450 SGPropertyNode *home = fgGetNode("/sim", true);
451 home->removeChild("fg-home", 0);
452 home = home->getChild("fg-home", 0, true);
453 home->setStringValue(dataPath.c_str());
454 home->setAttribute(SGPropertyNode::WRITE, false);
457 flightgear::Options* options = flightgear::Options::sharedInstance();
459 options->init(argc, argv, dataPath);
462 bool loadDefaults = options->shouldLoadDefaultConfig();
464 // Read global preferences from $FG_ROOT/preferences.xml
465 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
466 fgLoadProps("preferences.xml", globals->get_props());
467 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
469 // do not load user settings when reset to default is requested, or if
470 // told to explicitly ignore
471 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
473 SG_LOG(SG_GENERAL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
477 globals->loadUserSettings(dataPath);
480 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
481 }// of no-default-config selected
483 return flightgear::FG_OPTIONS_OK;
486 int fgInitAircraft(bool reinit)
488 // FIXME - use Documents/FlightGear/Aircraft
489 SGPath userAircraftDir = globals->get_fg_home();
490 userAircraftDir.append("Aircraft");
492 SGSharedPtr<Root> pkgRoot(new Root(userAircraftDir, FLIGHTGEAR_VERSION));
493 // set the http client later (too early in startup right now)
494 globals->setPackageRoot(pkgRoot);
496 // Scan user config files and command line for a specified aircraft.
498 SGPropertyNode* sim = fgGetNode("/sim", true);
499 sim->removeChildren("fg-aircraft");
500 // after reset, add aircraft dirs to props, needed for Nasal IO rules
501 string_list::const_iterator it;
503 for (it = globals->get_aircraft_paths().begin();
504 it != globals->get_aircraft_paths().end(); ++it, ++index)
506 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
507 n->setStringValue(*it);
508 n->setAttribute(SGPropertyNode::WRITE, false);
511 SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
512 aircraftProp->setAttribute(SGPropertyNode::PRESERVE, true);
514 flightgear::Options::sharedInstance()->initAircraft();
517 FindAndCacheAircraft f(globals->get_props());
518 if (!f.loadAircraft()) {
519 return flightgear::FG_OPTIONS_ERROR;
522 return flightgear::FG_OPTIONS_OK;
526 * Initialize vor/ndb/ils/fix list management and query systems (as
527 * well as simple airport db list)
528 * This is called multiple times in the case of a cache rebuild,
529 * to allow lengthy caching to take place in the background, without
530 * blocking the main/UI thread.
535 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
536 static bool doingRebuild = false;
537 if (doingRebuild || cache->isRebuildRequired()) {
539 bool finished = cache->rebuild();
541 // sleep to give the rebuild thread more time
542 SGTimeStamp::sleepForMSec(50);
547 FGTACANList *channellist = new FGTACANList;
548 globals->set_channellist( channellist );
550 SGPath path(globals->get_fg_root());
551 path.append( "Navaids/TACAN_freq.dat" );
552 flightgear::loadTacan(path, channellist);
557 // General house keeping initializations
558 bool fgInitGeneral() {
561 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
562 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
564 root = globals->get_fg_root();
565 if ( ! root.length() ) {
566 // No root path set? Then bail ...
567 SG_LOG( SG_GENERAL, SG_ALERT,
568 "Cannot continue without a path to the base package "
569 << "being defined." );
572 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
574 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
575 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
576 fgSetString("/sim/startup/browser-app", globals->get_browser());
578 simgear::Dir cwd(simgear::Dir::current());
579 SGPropertyNode *curr = fgGetNode("/sim", true);
580 curr->removeChild("fg-current", 0);
581 curr = curr->getChild("fg-current", 0, true);
582 curr->setStringValue(cwd.path().str());
583 curr->setAttribute(SGPropertyNode::WRITE, false);
585 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
586 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
590 // Write various configuraton values out to the logs
591 void fgOutputSettings()
593 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
594 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
596 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
597 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
598 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
600 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
601 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
604 // This is the top level init routine which calls all the other
605 // initialization routines. If you are adding a subsystem to flight
606 // gear, its initialization call should located in this routine.
607 // Returns non-zero if a problem encountered.
608 void fgCreateSubsystems(bool duringReset) {
610 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
611 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
613 ////////////////////////////////////////////////////////////////////
614 // Initialize the sound subsystem.
615 ////////////////////////////////////////////////////////////////////
616 // Sound manager uses an own subsystem group "SOUND" which is the last
617 // to be updated in every loop.
618 // Sound manager is updated last so it can use the CPU while the GPU
619 // is processing the scenery (doubled the frame-rate for me) -EMH-
620 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
622 ////////////////////////////////////////////////////////////////////
623 // Initialize the event manager subsystem.
624 ////////////////////////////////////////////////////////////////////
626 globals->get_event_mgr()->init();
627 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
629 ////////////////////////////////////////////////////////////////////
630 // Initialize the property interpolator subsystem. Put into the INIT
631 // group because the "nasal" subsystem may need it at GENERAL take-down.
632 ////////////////////////////////////////////////////////////////////
633 FGInterpolator* interp = new FGInterpolator;
634 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
635 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
636 SGPropertyNode::setInterpolationMgr(interp);
638 ////////////////////////////////////////////////////////////////////
639 // Add the FlightGear property utilities.
640 ////////////////////////////////////////////////////////////////////
641 globals->add_subsystem("properties", new FGProperties);
644 ////////////////////////////////////////////////////////////////////
645 // Add the performance monitoring system.
646 ////////////////////////////////////////////////////////////////////
647 globals->add_subsystem("performance-mon",
648 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
649 fgGetNode("/sim/performance-monitor", true)));
651 ////////////////////////////////////////////////////////////////////
652 // Initialize the material property subsystem.
653 ////////////////////////////////////////////////////////////////////
655 SGPath mpath( globals->get_fg_root() );
656 mpath.append( fgGetString("/sim/rendering/materials-file") );
657 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
658 globals->get_props()) ) {
659 throw sg_io_exception("Error loading materials file", mpath);
662 globals->add_subsystem( "http", new FGHTTPClient );
664 ////////////////////////////////////////////////////////////////////
665 // Initialize the scenery management subsystem.
666 ////////////////////////////////////////////////////////////////////
668 globals->get_scenery()->get_scene_graph()
669 ->addChild(simgear::Particles::getCommonRoot());
670 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
672 ////////////////////////////////////////////////////////////////////
673 // Initialize the flight model subsystem.
674 ////////////////////////////////////////////////////////////////////
676 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
678 ////////////////////////////////////////////////////////////////////
679 // Initialize the weather subsystem.
680 ////////////////////////////////////////////////////////////////////
682 // Initialize the weather modeling subsystem
683 globals->add_subsystem("environment", new FGEnvironmentMgr);
684 globals->add_subsystem("ephemeris", new Ephemeris);
686 ////////////////////////////////////////////////////////////////////
687 // Initialize the aircraft systems and instrumentation (before the
689 ////////////////////////////////////////////////////////////////////
691 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
692 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
693 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
694 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
696 ////////////////////////////////////////////////////////////////////
697 // Initialize the XML Autopilot subsystem.
698 ////////////////////////////////////////////////////////////////////
700 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
701 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
702 globals->add_subsystem( "route-manager", new FGRouteMgr );
704 ////////////////////////////////////////////////////////////////////
705 // Initialize the Input-Output subsystem
706 ////////////////////////////////////////////////////////////////////
707 globals->add_subsystem( "io", new FGIO );
709 ////////////////////////////////////////////////////////////////////
710 // Create and register the logger.
711 ////////////////////////////////////////////////////////////////////
713 globals->add_subsystem("logger", new FGLogger);
715 ////////////////////////////////////////////////////////////////////
716 // Create and register the XML GUI.
717 ////////////////////////////////////////////////////////////////////
719 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
721 //////////////////////////////////////////////////////////////////////
722 // Initialize the 2D cloud subsystem.
723 ////////////////////////////////////////////////////////////////////
724 fgGetBool("/sim/rendering/bump-mapping", false);
726 ////////////////////////////////////////////////////////////////////
727 // Initialize the canvas 2d drawing subsystem.
728 ////////////////////////////////////////////////////////////////////
729 simgear::canvas::Canvas::setSystemAdapter(
730 simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
732 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
733 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
735 ////////////////////////////////////////////////////////////////////
736 // Initialize the ATC subsystem
737 ////////////////////////////////////////////////////////////////////
738 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
740 ////////////////////////////////////////////////////////////////////
741 // Initialize multiplayer subsystem
742 ////////////////////////////////////////////////////////////////////
744 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
746 ////////////////////////////////////////////////////////////////////
747 // Initialise the AI Model Manager
748 ////////////////////////////////////////////////////////////////////
749 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
750 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
751 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
754 // It's probably a good idea to initialize the top level traffic manager
755 // After the AI and ATC systems have been initialized properly.
756 // AI Traffic manager
757 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
759 ////////////////////////////////////////////////////////////////////
760 // Add a new 2D panel.
761 ////////////////////////////////////////////////////////////////////
763 fgSetArchivable("/sim/panel/visibility");
764 fgSetArchivable("/sim/panel/x-offset");
765 fgSetArchivable("/sim/panel/y-offset");
766 fgSetArchivable("/sim/panel/jitter");
768 ////////////////////////////////////////////////////////////////////
769 // Initialize the controls subsystem.
770 ////////////////////////////////////////////////////////////////////
772 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
774 ////////////////////////////////////////////////////////////////////
775 // Initialize the input subsystem.
776 ////////////////////////////////////////////////////////////////////
778 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
781 ////////////////////////////////////////////////////////////////////
782 // Initialize the replay subsystem
783 ////////////////////////////////////////////////////////////////////
784 globals->add_subsystem("replay", new FGReplay);
785 globals->add_subsystem("history", new FGFlightHistory);
787 #ifdef ENABLE_AUDIO_SUPPORT
788 ////////////////////////////////////////////////////////////////////
789 // Initialize the sound-effects subsystem.
790 ////////////////////////////////////////////////////////////////////
791 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
795 ////////////////////////////////////////////////////////////////////
796 // Initialize the FGCom subsystem.
797 ////////////////////////////////////////////////////////////////////
798 globals->add_subsystem("fgcom", new FGCom);
802 SGSubsystem * httpd = flightgear::http::FGHttpd::createInstance( fgGetNode(flightgear::http::PROPERTY_ROOT) );
804 globals->add_subsystem("httpd", httpd );
807 ////////////////////////////////////////////////////////////////////
808 // Initialize the lighting subsystem.
809 ////////////////////////////////////////////////////////////////////
811 // ordering here is important : Nasal (via events), then models, then views
813 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
814 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
817 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
818 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
820 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
822 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
823 SGSubsystemMgr::DISPLAY);
826 void fgPostInitSubsystems()
831 ////////////////////////////////////////////////////////////////////////
832 // Initialize the Nasal interpreter.
833 // Do this last, so that the loaded scripts see initialized state
834 ////////////////////////////////////////////////////////////////////////
835 FGNasalSys* nasal = new FGNasalSys();
836 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
838 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
840 // Ensure IOrules and path validation are working properly by trying to
841 // access a folder/file which should never be accessible.
842 const char* no_access_path =
848 if( fgValidatePath(no_access_path, true) )
853 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
855 if( fgValidatePath(no_access_path, false) )
860 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
863 // initialize methods that depend on other subsystems.
865 globals->get_subsystem_mgr()->postinit();
866 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
868 ////////////////////////////////////////////////////////////////////////
869 // End of subsystem initialization.
870 ////////////////////////////////////////////////////////////////////
872 fgSetBool("/sim/crashed", false);
873 fgSetBool("/sim/initialized", true);
875 SG_LOG( SG_GENERAL, SG_INFO, endl);
878 // re-position is a simplified version of the traditional (legacy)
879 // reset procedure. We only need to poke systems which will be upset by
880 // a sudden change in aircraft position. Since this potentially includes
881 // Nasal, we trigger the 'reinit' signal.
882 void fgStartReposition()
884 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
885 SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
887 // ensure we are frozen
888 bool freeze = master_freeze->getBoolValue();
890 master_freeze->setBoolValue(true);
893 // set this signal so Nasal scripts can take action.
894 fgSetBool("/sim/signals/reinit", true);
895 fgSetBool("/sim/crashed", false);
897 FDMShell* fdm = static_cast<FDMShell*>(globals->get_subsystem("flight"));
900 // update our position based on current presets
901 // this will mark position as needed finalized which we'll do in the
903 flightgear::initPosition();
905 simgear::SGTerraSync* terraSync =
906 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
908 terraSync->reposition();
911 // Initialize the FDM
912 globals->get_subsystem("flight")->reinit();
914 // reset replay buffers
915 globals->get_subsystem("replay")->reinit();
917 // ugly: finalizePosition waits for METAR to arrive for the new airport.
918 // we don't re-init the environment manager here, since historically we did
919 // not, and doing so seems to have other issues. All that's needed is to
920 // schedule METAR fetch immediately, so it's available for finalizePosition.
921 // So we manually extract the METAR-fetching component inside the environment
922 // manager, and re-init that.
923 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
925 envMgr->get_subsystem("realwx")->reinit();
928 // need to bind FDMshell again, since we manually unbound it above...
931 // need to reset aircraft (systems/instruments/autopilot)
932 // so they can adapt to current environment
933 globals->get_subsystem("systems")->reinit();
934 globals->get_subsystem("instrumentation")->reinit();
935 globals->get_subsystem("xml-autopilot")->reinit();
937 // setup state to end re-init
938 fgSetBool("/sim/signals/reinit", false);
940 master_freeze->setBoolValue(false);
942 fgSetBool("/sim/sceneryloaded",false);
945 void fgStartNewReset()
947 SGPropertyNode_ptr preserved(new SGPropertyNode);
949 if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
950 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
952 fgSetBool("/sim/signals/reinit", true);
953 fgSetBool("/sim/freeze/master", true);
955 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
956 // Nasal is manually inited in fgPostInit, ensure it's already shutdown
957 // before other subsystems, so Nasal listeners don't fire during shutdonw
958 SGSubsystem* nasal = subsystemManger->get_subsystem("nasal");
961 subsystemManger->remove("nasal");
963 subsystemManger->shutdown();
964 subsystemManger->unbind();
966 // remove most subsystems, with a few exceptions.
967 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
968 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
969 const string_list& names(grp->member_names());
970 string_list::const_iterator it;
971 for (it = names.begin(); it != names.end(); ++it) {
972 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
973 || (*it == "lighting"))
979 subsystemManger->remove(it->c_str());
980 } catch (std::exception& e) {
981 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
983 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
986 // don't delete here, dropping the ref should be sufficient
988 } // of top-level groups iteration
990 FGRenderer* render = globals->get_renderer();
991 // needed or we crash in multi-threaded OSG mode
992 render->getViewer()->stopThreading();
994 // order is important here since tile-manager shutdown needs to
995 // access the scenery object
996 globals->set_tile_mgr(NULL);
997 globals->set_scenery(NULL);
998 FGScenery::getPagerSingleton()->clearRequests();
999 flightgear::CameraGroup::setDefault(NULL);
1001 // don't cancel the pager until after shutdown, since AIModels (and
1002 // potentially others) can queue delete requests on the pager.
1003 render->getViewer()->getDatabasePager()->cancel();
1004 render->getViewer()->getDatabasePager()->clear();
1006 osgDB::Registry::instance()->clearObjectCache();
1008 // preserve the event handler; re-creating it would entail fixing the
1010 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
1012 globals->set_renderer(NULL);
1013 globals->set_matlib(NULL);
1014 globals->set_chatter_queue(NULL);
1016 simgear::clearEffectCache();
1017 simgear::SGModelLib::resetPropertyRoot();
1019 simgear::GlobalParticleCallback::setSwitch(NULL);
1021 globals->resetPropertyRoot();
1022 // otherwise channels are duplicated
1023 globals->get_channel_options_list()->clear();
1025 fgInitConfig(0, NULL, true);
1026 fgInitGeneral(); // all of this?
1028 flightgear::Options::sharedInstance()->processOptions();
1030 // PRESERVED properties over-write state from options, intentionally
1031 if ( copyProperties(preserved, globals->get_props()) ) {
1032 SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1034 SG_LOG( SG_GENERAL, SG_INFO,
1035 "Some errors restoring preserved state (read-only props?)" );
1038 fgGetNode("/sim")->removeChild("aircraft-dir");
1039 fgInitAircraft(true);
1041 render = new FGRenderer;
1042 render->setEventHandler(eventHandler);
1043 eventHandler->reset();
1044 globals->set_renderer(render);
1046 render->setViewer(viewer.get());
1048 viewer->getDatabasePager()->setUpThreads(1, 1);
1050 // must do this before splashinit for Rembrandt
1051 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1052 render->splashinit();
1053 viewer->startThreading();
1055 fgOSResetProperties();
1057 // init some things manually
1058 // which do not follow the regular init pattern
1060 globals->get_event_mgr()->init();
1061 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1063 globals->set_matlib( new SGMaterialLib );
1065 // terra-sync needs the property tree root, pass it back in
1066 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1067 terra_sync->setRoot(globals->get_props());
1069 fgSetBool("/sim/signals/reinit", false);
1070 fgSetBool("/sim/freeze/master", false);
1071 fgSetBool("/sim/sceneryloaded",false);