1 // globals.cxx -- Global state that needs to be shared among the sim modules
3 // Written by Curtis Olson, started July 2000.
5 // Copyright (C) 2000 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 Foundation,
19 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 #include <boost/foreach.hpp>
30 #include <osgViewer/Viewer>
31 #include <osgDB/Registry>
33 #include <simgear/structure/commands.hxx>
34 #include <simgear/misc/sg_path.hxx>
35 #include <simgear/misc/sg_dir.hxx>
36 #include <simgear/timing/sg_time.hxx>
37 #include <simgear/ephemeris/ephemeris.hxx>
38 #include <simgear/scene/material/matlib.hxx>
39 #include <simgear/structure/subsystem_mgr.hxx>
40 #include <simgear/structure/event_mgr.hxx>
41 #include <simgear/sound/soundmgr_openal.hxx>
42 #include <simgear/misc/ResourceManager.hxx>
43 #include <simgear/props/propertyObject.hxx>
44 #include <simgear/props/props_io.hxx>
45 #include <simgear/scene/model/modellib.hxx>
47 #include <Aircraft/controls.hxx>
48 #include <Airports/runways.hxx>
49 #include <Autopilot/route_mgr.hxx>
50 #include <GUI/FGFontCache.hxx>
52 #include <MultiPlayer/multiplaymgr.hxx>
53 #include <Scenery/scenery.hxx>
54 #include <Scenery/tilemgr.hxx>
55 #include <Navaids/navlist.hxx>
56 #include <Viewer/renderer.hxx>
57 #include <Viewer/viewmgr.hxx>
58 #include <Sound/sample_queue.hxx>
60 #include "globals.hxx"
63 #include "fg_props.hxx"
66 class AircraftResourceProvider : public simgear::ResourceProvider
69 AircraftResourceProvider() :
70 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
74 virtual SGPath resolve(const std::string& aResource, SGPath&) const
76 string_list pieces(sgPathBranchSplit(aResource));
77 if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
78 return SGPath(); // not an Aircraft path
81 // test against the aircraft-dir property
82 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
83 string_list aircraftDirPieces(sgPathBranchSplit(aircraftDir));
84 if (!aircraftDirPieces.empty() && (aircraftDirPieces.back() == pieces[1])) {
85 // current aircraft-dir matches resource aircraft
86 SGPath r(aircraftDir);
87 for (unsigned int i=2; i<pieces.size(); ++i) {
96 // try each aircraft dir in turn
97 std::string res(aResource, 9); // resource path with 'Aircraft/' removed
98 const string_list& dirs(globals->get_aircraft_paths());
99 string_list::const_iterator it = dirs.begin();
100 for (; it != dirs.end(); ++it) {
105 } // of aircraft path iteration
107 return SGPath(); // not found
111 class CurrentAircraftDirProvider : public simgear::ResourceProvider
114 CurrentAircraftDirProvider() :
115 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
119 virtual SGPath resolve(const std::string& aResource, SGPath&) const
121 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
122 SGPath p(aircraftDir);
124 return p.exists() ? p : SGPath();
128 ////////////////////////////////////////////////////////////////////////
129 // Implementation of FGGlobals.
130 ////////////////////////////////////////////////////////////////////////
133 FGGlobals *globals = NULL;
137 FGGlobals::FGGlobals() :
138 renderer( new FGRenderer ),
139 subsystem_mgr( new SGSubsystemMgr ),
140 event_mgr( new SGEventMgr ),
149 commands( SGCommandMgr::instance() ),
150 channel_options_list( NULL ),
151 initial_waypoints( NULL ),
152 fontcache ( new FGFontCache ),
154 haveUserSettings(false),
157 SGPropertyNode* root = new SGPropertyNode;
158 props = SGPropertyNode_ptr(root);
159 locale = new FGLocale(props);
161 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
162 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
166 void FGGlobals::initProperties()
168 simgear::PropertyObjectBase::setDefaultRoot(props);
170 positionLon = props->getNode("position/longitude-deg", true);
171 positionLat = props->getNode("position/latitude-deg", true);
172 positionAlt = props->getNode("position/altitude-ft", true);
174 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
175 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
176 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
178 orientPitch = props->getNode("orientation/pitch-deg", true);
179 orientHeading = props->getNode("orientation/heading-deg", true);
180 orientRoll = props->getNode("orientation/roll-deg", true);
185 FGGlobals::~FGGlobals()
187 // save user settings (unless already saved)
190 // The AIModels manager performs a number of actions upon
191 // Shutdown that implicitly assume that other subsystems
192 // are still operational (Due to the dynamic allocation and
193 // deallocation of AIModel objects. To ensure we can safely
194 // shut down all subsystems, make sure we take down the
195 // AIModels system first.
196 SGSubsystemRef ai = subsystem_mgr->get_subsystem("ai-model");
198 subsystem_mgr->remove("ai-model");
200 ai.clear(); // ensure AI is deleted now, not at end of this method
203 subsystem_mgr->shutdown();
204 subsystem_mgr->unbind();
206 subsystem_mgr->remove("aircraft-model");
207 subsystem_mgr->remove("tile-manager");
208 subsystem_mgr->remove("model-manager");
211 osg::ref_ptr<osgViewer::Viewer> vw(renderer->getViewer());
213 // https://code.google.com/p/flightgear-bugs/issues/detail?id=1291
214 // explicitly stop trheading before we delete the renderer or
215 // viewMgr (which ultimately holds refs to the CameraGroup, and
220 // don't cancel the pager until after shutdown, since AIModels (and
221 // potentially others) can queue delete requests on the pager.
222 if (vw && vw->getDatabasePager()) {
223 vw->getDatabasePager()->cancel();
224 vw->getDatabasePager()->clear();
227 osgDB::Registry::instance()->clearObjectCache();
229 // renderer touches subsystems during its destruction
232 _chatter_queue.clear();
234 delete subsystem_mgr;
235 subsystem_mgr = NULL; // important so ::get_subsystem returns NULL
236 vw = 0; // don't delete the viewer until now
241 delete channel_options_list;
242 delete initial_waypoints;
246 simgear::PropertyObjectBase::setDefaultRoot(NULL);
247 simgear::SGModelLib::resetPropertyRoot();
259 // set the fg_root path
260 void FGGlobals::set_fg_root (const std::string &root) {
262 fg_root = tmp.realpath();
264 // append /data to root if it exists
265 tmp.append( "data" );
266 tmp.append( "version" );
267 if ( tmp.exists() ) {
268 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
270 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
271 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
272 << fg_root << "'\n***\n***");
275 // remove /sim/fg-root before writing to prevent hijacking
276 SGPropertyNode *n = fgGetNode("/sim", true);
277 n->removeChild("fg-root", 0);
278 n = n->getChild("fg-root", 0, true);
279 n->setStringValue(fg_root.c_str());
280 n->setAttribute(SGPropertyNode::WRITE, false);
282 simgear::ResourceManager::instance()->addBasePath(fg_root,
283 simgear::ResourceManager::PRIORITY_DEFAULT);
286 // set the fg_home path
287 void FGGlobals::set_fg_home (const std::string &home) {
289 fg_home = tmp.realpath();
292 PathList FGGlobals::get_data_paths() const
294 PathList r(additional_data_paths);
295 r.push_back(SGPath(fg_root));
299 PathList FGGlobals::get_data_paths(const std::string& suffix) const
302 BOOST_FOREACH(SGPath p, get_data_paths()) {
312 void FGGlobals::append_data_path(const SGPath& path)
314 if (!path.exists()) {
315 SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
318 additional_data_paths.push_back(path);
321 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
323 BOOST_FOREACH(SGPath p, additional_data_paths) {
324 p.append(pathSuffix);
330 SGPath rootPath(fg_root);
331 rootPath.append(pathSuffix);
332 if (rootPath.exists()) {
336 SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
340 void FGGlobals::append_fg_scenery (const std::string &paths)
342 // fg_scenery.clear();
343 SGPropertyNode* sim = fgGetNode("/sim", true);
345 // find first unused fg-scenery property in /sim
347 while (sim->getChild("fg-scenery", propIndex) != NULL) {
351 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
352 SGPath abspath(path.realpath());
353 if (!abspath.exists()) {
354 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
358 // check for duplicates
359 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
360 if (ex != fg_scenery.end()) {
361 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
365 simgear::Dir dir(abspath);
366 SGPath terrainDir(dir.file("Terrain"));
367 SGPath objectsDir(dir.file("Objects"));
369 // this code used to add *either* the base dir, OR add the
370 // Terrain and Objects subdirs, but the conditional logic was commented
371 // out, such that all three dirs are added. Unfortunately there's
372 // no information as to why the change was made.
373 fg_scenery.push_back(abspath.str());
375 if (terrainDir.exists()) {
376 fg_scenery.push_back(terrainDir.str());
379 if (objectsDir.exists()) {
380 fg_scenery.push_back(objectsDir.str());
383 // insert a marker for FGTileEntry::load(), so that
384 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
385 // "B/Terrain", "B/Objects", ""]
386 fg_scenery.push_back("");
388 // make scenery dirs available to Nasal
389 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
390 n->setStringValue(abspath.str());
391 n->setAttribute(SGPropertyNode::WRITE, false);
393 // temporary fix so these values survive reset
394 n->setAttribute(SGPropertyNode::PRESERVE, true);
395 } // of path list iteration
398 void FGGlobals::append_aircraft_path(const std::string& path)
400 SGPath dirPath(path);
401 if (!dirPath.exists()) {
402 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft path not found:" << path);
406 SGPath acSubdir(dirPath);
407 acSubdir.append("Aircraft");
408 if (acSubdir.exists()) {
409 SG_LOG(SG_GENERAL, SG_WARN, "Specified an aircraft-dir with an 'Aircraft' subdirectory:" << dirPath
410 << ", will instead use child directory:" << acSubdir);
414 std::string abspath = dirPath.realpath();
415 unsigned int index = fg_aircraft_dirs.size();
416 fg_aircraft_dirs.push_back(abspath);
418 // make aircraft dirs available to Nasal
419 SGPropertyNode* sim = fgGetNode("/sim", true);
420 sim->removeChild("fg-aircraft", index);
421 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
422 n->setStringValue(abspath);
423 n->setAttribute(SGPropertyNode::WRITE, false);
426 void FGGlobals::append_aircraft_paths(const std::string& path)
428 string_list paths = sgPathSplit(path);
429 for (unsigned int p = 0; p<paths.size(); ++p) {
430 append_aircraft_path(paths[p]);
434 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
436 return simgear::ResourceManager::instance()->findPath(branch);
439 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
441 return simgear::ResourceManager::instance()->findPath(branch);
444 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
446 return simgear::ResourceManager::instance()
447 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
451 FGGlobals::get_renderer () const
456 void FGGlobals::set_renderer(FGRenderer *render)
458 if (render == renderer) {
467 FGGlobals::get_subsystem_mgr () const
469 return subsystem_mgr;
473 FGGlobals::get_subsystem (const char * name)
475 if (!subsystem_mgr) {
479 return subsystem_mgr->get_subsystem(name);
483 FGGlobals::add_subsystem (const char * name,
484 SGSubsystem * subsystem,
485 SGSubsystemMgr::GroupType type,
488 subsystem_mgr->add(name, subsystem, type, min_time_sec);
492 FGGlobals::get_soundmgr () const
495 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
501 FGGlobals::get_event_mgr () const
507 FGGlobals::get_aircraft_position() const
509 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
510 positionLat->getDoubleValue(),
511 positionAlt->getDoubleValue());
515 FGGlobals::get_aircraft_position_cart() const
517 return SGVec3d::fromGeod(get_aircraft_position());
520 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
522 heading = orientHeading->getDoubleValue();
523 pitch = orientPitch->getDoubleValue();
524 roll = orientRoll->getDoubleValue();
528 FGGlobals::get_view_position() const
530 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
531 viewLat->getDoubleValue(),
532 viewAlt->getDoubleValue());
536 FGGlobals::get_view_position_cart() const
538 return SGVec3d::fromGeod(get_view_position());
541 static void treeDumpRefCounts(int depth, SGPropertyNode* nd)
543 for (int i=0; i<nd->nChildren(); ++i) {
544 SGPropertyNode* cp = nd->getChild(i);
545 if (SGReferenced::count(cp) > 1) {
546 SG_LOG(SG_GENERAL, SG_INFO, "\t" << cp->getPath() << " refcount:" << SGReferenced::count(cp));
549 treeDumpRefCounts(depth + 1, cp);
553 static void treeClearAliases(SGPropertyNode* nd)
559 for (int i=0; i<nd->nChildren(); ++i) {
560 SGPropertyNode* cp = nd->getChild(i);
561 treeClearAliases(cp);
566 FGGlobals::resetPropertyRoot()
572 // we don't strictly need to clear these (they will be reset when we
573 // initProperties again), but trying to reduce false-positives when dumping
582 orientHeading.clear();
585 // clear aliases so ref-counts are accurate when dumped
586 treeClearAliases(props);
588 SG_LOG(SG_GENERAL, SG_INFO, "root props refcount:" << props.getNumRefs());
589 treeDumpRefCounts(0, props);
591 //BaseStackSnapshot::dumpAll(std::cout);
593 props = new SGPropertyNode;
595 locale = new FGLocale(props);
597 // remove /sim/fg-root before writing to prevent hijacking
598 SGPropertyNode *n = props->getNode("/sim", true);
599 n->removeChild("fg-root", 0);
600 n = n->getChild("fg-root", 0, true);
601 n->setStringValue(fg_root.c_str());
602 n->setAttribute(SGPropertyNode::WRITE, false);
605 static std::string autosaveName()
607 std::ostringstream os;
608 string_list versionParts = simgear::strutils::split(VERSION, ".");
609 if (versionParts.size() < 2) {
610 return "autosave.xml";
613 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
617 // Load user settings from autosave.xml
619 FGGlobals::loadUserSettings(const SGPath& dataPath)
621 // remember that we have (tried) to load any existing autsave.xml
622 haveUserSettings = true;
624 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
625 SGPropertyNode autosave;
626 if (autosaveFile.exists()) {
627 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
629 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
630 } catch (sg_exception& e) {
631 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
632 << "(from " << e.getOrigin() << ")");
635 copyProperties(&autosave, globals->get_props());
638 // Save user settings in autosave.xml
640 FGGlobals::saveUserSettings()
642 // only save settings when we have (tried) to load the previous
643 // settings (otherwise user data was lost)
644 if (!haveUserSettings)
647 if (fgGetBool("/sim/startup/save-on-exit")) {
648 // don't save settings more than once on shutdown
649 haveUserSettings = false;
651 SGPath autosaveFile(globals->get_fg_home());
652 autosaveFile.append(autosaveName());
653 autosaveFile.create_dir( 0700 );
654 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
656 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
657 } catch (const sg_exception &e) {
658 guiErrorMessage("Error writing autosave:", e);
660 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
665 FGGlobals::get_current_view () const
667 return viewmgr->get_current_view();
670 long int FGGlobals::get_warp() const
672 return fgGetInt("/sim/time/warp");
675 void FGGlobals::set_warp( long int w )
677 fgSetInt("/sim/time/warp", w);
680 long int FGGlobals::get_warp_delta() const
682 return fgGetInt("/sim/time/warp-delta");
685 void FGGlobals::set_warp_delta( long int d )
687 fgSetInt("/sim/time/warp-delta", d);
690 FGScenery* FGGlobals::get_scenery () const
692 return _scenery.get();
695 void FGGlobals::set_scenery ( FGScenery *s )
700 FGTileMgr* FGGlobals::get_tile_mgr () const
702 return _tile_mgr.get();
705 void FGGlobals::set_tile_mgr ( FGTileMgr *t )
710 void FGGlobals::set_matlib( SGMaterialLib *m )
715 FGSampleQueue* FGGlobals::get_chatter_queue() const
717 return _chatter_queue;
720 void FGGlobals::set_chatter_queue(FGSampleQueue* queue)
722 _chatter_queue = queue;
725 void FGGlobals::addListenerToCleanup(SGPropertyChangeListener* l)
727 _listeners_to_cleanup.push_back(l);
730 void FGGlobals::cleanupListeners()
732 SGPropertyChangeListenerVec::iterator i = _listeners_to_cleanup.begin();
733 for (; i != _listeners_to_cleanup.end(); ++i) {
736 _listeners_to_cleanup.clear();
739 // end of globals.cxx